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.pymyapp/
__init__.py
auth/
routes.py
models.py
config.py
wsgi.pycreate_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 appfrom 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
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 coffeeWas this page helpful?
Let us know how we did
