The application factory pattern helps create Flask apps in a flexible way. It lets you make multiple app instances with different settings easily.
Application factory pattern deep dive in Flask
def create_app(config_name=None): app = Flask(__name__) if config_name: app.config.from_object(config_name) # Initialize extensions here # Register blueprints here return app
The function create_app returns a new Flask app instance.
You can pass configuration names or objects to customize the app.
def create_app(): app = Flask(__name__) return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config_name) return app
def create_app(): app = Flask(__name__) from .extensions import db db.init_app(app) from .routes import main_bp app.register_blueprint(main_bp) return app
This example shows a Flask app created using the application factory pattern. It defines a blueprint with a simple route, then the create_app function creates the app, loads optional config, and registers the blueprint. Running this script starts the app.
from flask import Flask, Blueprint main_bp = Blueprint('main', __name__) @main_bp.route('/') def home(): return 'Hello from the factory app!' def create_app(config_name=None): app = Flask(__name__) if config_name: app.config.from_object(config_name) app.register_blueprint(main_bp) return app if __name__ == '__main__': app = create_app() app.run(debug=True)
Using the factory pattern avoids global Flask app instances, which helps testing and scaling.
Extensions like Flask-SQLAlchemy require init_app(app) inside the factory.
Blueprints help organize routes and are registered inside the factory function.
The application factory pattern creates Flask apps inside a function for flexibility.
It supports multiple configurations and clean app setup.
Use it to improve testing, modularity, and extension initialization.