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
text
myapp/
__init__.py
auth/
routes.py
models.py
config.py
wsgi.pytext
myapp/
__init__.py
auth/
routes.py
models.py
config.py
wsgi.pycreate_app example
myapp/__init__.pymyapp/__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 apppython
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
wsgi.pywsgi.py:
python
from myapp import create_app
app = create_app()python
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.
Visualize it
Here’s the sequence of steps create_app()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"]
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
