Application Factory Pattern
The application factory pattern builds the app in a function:
create_app()
This is the recommended pattern for larger Flask apps.
Why use a factory?
Section titled “Why use a factory?”- enables easy testing (create a test app)
- supports multiple environments (dev/test/prod)
- avoids import-time side effects
- helps extensions initialize consistently
Example structure
Section titled “Example structure”myapp/
__init__.py
auth/
routes.py
models.py
config.py
wsgi.pycreate_app example
Section titled “create_app example”myapp/__init__.py:
from flask import Flask
from .extensions import db, login_manager
from .auth.routes import auth_bp
def create_app(config_object="config.DevelopmentConfig"):
app = Flask(__name__)
app.config.from_object(config_object)
db.init_app(app)
login_manager.init_app(app)
app.register_blueprint(auth_bp, url_prefix="/auth")
return appwsgi entrypoint
Section titled “wsgi entrypoint”wsgi.py:
from myapp import create_app
app = create_app()Now you can run:
gunicorn "wsgi:app"
Key takeaway
Section titled “Key takeaway”Factories make your app predictable and keep global state under control.
Visualize it
Section titled “Visualize it”Here’s the sequence of steps create_app() runs to build a fully configured Flask app.
flowchart TD A["create_app()"] --> B["Create Flask app"] B --> C["Load config"] C --> D["Initialize extensions (db, login_manager)"] D --> E["Register blueprints"] E --> F["Return app"]
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading