Skip to content

Application Factory Pattern

The application factory pattern builds the app in a function:

  • create_app()create_app()

This is the recommended pattern for larger Flask apps.

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

myapp/
  __init__.py
  auth/
    routes.py
  models.py
config.py
wsgi.py
myapp/
  __init__.py
  auth/
    routes.py
  models.py
config.py
wsgi.py

create_app example

myapp/__init__.pymyapp/__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 app
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 entrypoint

wsgi.pywsgi.py:

from myapp import create_app
 
app = create_app()
from myapp import create_app
 
app = create_app()

Now you can run:

  • gunicorn "wsgi:app"gunicorn "wsgi:app"

Key takeaway

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

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did