7 Large App Sturcture

Last edited

flasky/
├── app/ # typically named app, can be app specific though
│   ├── templates/
│   ├── static/
│   ├── main/
│   │   ├── __init__.py
│   │   ├── errors.py # error handlers
│   │   ├── forms.py
│   │   └── views.py # routes
│   ├── __init__.py
│   ├── email.py
│   └── models.py
├── migrations/ 
├── tests/
│   ├── __init__.py
│   └── test*.py
├── venv/
├── pyproject.toml
├── config.py
└── flasky.py # application instance is defined

Blueprints

Pithy

Blueprints are the same as registering routes to an app. The only difference is they’re only manually registered, so the app can pick them up whenever it wants rather needing to register at import time.

Blueprints are like an application. Except that when you define then they are not active until the blueprint is registered with an application.

The point of this is to allow you define the blueprints are start time and the app a runtime which is more flexible to configuration.

Blueprint("blueprint_name", __name__)

The blueprints get registered when the app is created

def create_app(config_name):
    # ... 

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)
    
    return app

Note

Clue does this exact pattern, they both define the register

errors = Blueprint("errors", __name__)

@errors.app_errorhandler(404)
def ...
@errors.app_errorhandler(500)
def ...

Only difference is they don’t have the create_app() they just register at import time.

# 
app = Flask("clue_api")
from clue.api.v1.fetchers import fetchers_api
# ...
app.register_blueprint(healthz)
app.register_blueprint(api)
app.register_blueprint(errors)
app.register_blueprint(fetchers_api)

Both options seem good, create_app might have easier testing because calling import clue.app immediately builds the app using whatever config envrionment it has.