Skip to content

Application Factory Pattern

The application factory pattern builds the app in a function:

  • create_app()

This is the recommended pattern for larger Flask apps.

  • enables easy testing (create a test app)
  • supports multiple environments (dev/test/prod)
  • avoids import-time side effects
  • helps extensions initialize consistently
text
myapp/
  __init__.py
  auth/
    routes.py
  models.py
config.py
wsgi.py

myapp/__init__.py:

python
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 app

wsgi.py:

python
from myapp import create_app
 
app = create_app()

Now you can run:

  • gunicorn "wsgi:app"

Factories make your app predictable and keep global state under control.

Here’s the sequence of steps create_app() runs to build a fully configured Flask app.

diagram Application factory flow mermaid
create_app() builds the Flask app, loads config, initializes extensions, registers blueprints, then returns the app

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading