Flask Project Structure

Why Project Structure Matters

A well-organized project structure is crucial for Flask applications, especially as they grow in complexity. A good structure makes your code more maintainable, scalable, and easier to understand for new developers joining your project.

While Flask is flexible and doesn't enforce a specific project structure, there are several conventions and best practices that have emerged in the Flask community.

Basic Project Structure

For small to medium-sized Flask applications, the following structure is recommended:

my_flask_app/
├── app/
│   ├── __init__.py          # Initialize the app and bring together components
│   ├── routes/              # Route definitions
│   │   ├── __init__.py
│   │   ├── main.py          # Main routes
│   │   └── auth.py          # Authentication routes
│   ├── models.py            # Database models
│   ├── forms.py             # Form classes using Flask-WTF
│   ├── static/              # Static files (CSS, JS, images)
│   │   ├── css/
│   │   ├── js/
│   │   └── img/
│   └── templates/           # Jinja2 templates
│       ├── base.html        # Base template with common elements
│       ├── index.html       # Home page
│       └── auth/            # Authentication templates
│           ├── login.html
│           └── register.html
├── config.py                # Configuration settings
├── requirements.txt         # Project dependencies
├── run.py                   # Application entry point
└── README.md                # Project documentation

This structure separates concerns and follows the Model-View-Controller (MVC) pattern, which is a common approach in web development.

Key Components Explained

Component Purpose
app/ The main application package containing all your application code.
app/__init__.py Initializes your Flask application and brings together various components.
app/routes/ Contains route definitions organized by feature or function.
app/models.py Defines database models using an ORM like SQLAlchemy.
app/static/ Contains static files like CSS, JavaScript, and images.
app/templates/ Contains Jinja2 templates for rendering HTML.
config.py Configuration settings for different environments (development, testing, production).
run.py Entry point for running the application.

The Application Factory Pattern

For larger applications, the "Application Factory" pattern is recommended. This pattern creates the application object inside a function rather than at the module level, which allows for multiple instances of the app and easier testing.

# app/__init__.py
from flask import Flask

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    
    # Initialize extensions
    db.init_app(app)
    migrate.init_app(app, db)
    
    # Register blueprints
    from app.routes.main import main
    app.register_blueprint(main)
    
    return app

This approach is more flexible and makes your application more modular. It's especially useful when you need to create different instances of your application with different configurations, such as for testing.

Using Blueprints

Blueprints are a powerful feature in Flask that allow you to organize your application into distinct components. They're especially useful for larger applications with multiple features.

# app/routes/main.py
from flask import Blueprint, render_template

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return render_template('index.html')

Blueprints help you organize related routes, templates, and static files together, making your codebase more maintainable as it grows.

Best Practices

  • Separation of concerns: Keep different parts of your application separate (routes, models, templates).
  • Use blueprints: Organize your application into logical components using blueprints.
  • Configuration: Keep configuration separate from application code and use environment variables for sensitive information.
  • Testing: Structure your application to make testing easier, using the application factory pattern.
  • Documentation: Include a README.md file with setup instructions and project information.
  • Dependencies: Use a requirements.txt file to track dependencies.

Create Project Structure Scripts

You can use the following simple scripts to automatically create a basic Flask project structure in your current directory. These scripts will create all the necessary folders and empty files to help you get started quickly.

Windows Batch Script (create_flask_structure.bat)

@echo off
echo Creating Flask application structure...

:: Create main application folder and files
mkdir app
cd app
type nul > __init__.py
type nul > models.py
type nul > forms.py

:: Create routes directory and files
mkdir routes
cd routes
type nul > __init__.py
type nul > main.py
type nul > auth.py
cd ..

:: Create static directories
mkdir static
cd static
mkdir css
mkdir js
mkdir img
cd css
type nul > main.css
cd ..
cd js
type nul > main.js
cd ..
cd ..

:: Create templates directory and files
mkdir templates
cd templates
type nul > base.html
type nul > index.html
mkdir auth
cd auth
type nul > login.html
type nul > register.html
cd ..
cd ..

:: Create config and main files
cd ..
type nul > config.py
type nul > run.py
type nul > requirements.txt
type nul > README.md

echo.
echo Flask application structure created successfully!
echo You can now start developing your Flask app.

These scripts create an empty Flask project structure with all necessary directories and empty files, following the standard Flask project organization. Save the script as either create_flask_structure.bat (Windows) or create_flask_structure.sh (Linux/Mac) and run it in the directory where you want to create your new Flask project.

Helpful Notes

  • After creating the structure, you'll need to populate the files with your application code.
  • Flask is flexible by design. The structure suggested here is a common convention, but you can adapt it to your specific needs.