Skip to content

App Structure

Evolving from simple scripts to a maintainable project structure, the recommended pattern is "Application Factory + Blueprints."

Minimal Structure:

flask-demo/
  app.py

Recommended Structure (Application Factory):

flask-demo/
  app/
    __init__.py      # create_app factory
    views.py         # Routes/views
    extensions.py    # Third-party extension instantiation
    models.py        # Data models (optional)
    templates/       # Jinja2 templates
    static/          # Static files
  instance/
    config.py        # Private config (not in version control)
  .env               # Environment variables (optional)
  wsgi.py            # Production entry point (optional)

Application Factory Example:

python
# app/__init__.py
from flask import Flask

def create_app(config_object=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY="dev")
    if config_object:
        app.config.from_object(config_object)
    # Lazy import and register blueprints
    from .views import bp as main_bp
    app.register_blueprint(main_bp)
    return app

Blueprint and Views:

python
# app/views.py
from flask import Blueprint

bp = Blueprint("main", __name__)

@bp.get("/")
def index():
    return "Hello from Blueprint"

Development Run:

bash
export FLASK_APP=app:create_app
flask run --debug

Content is for learning and research only.