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 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 each time it is called.
You can pass configuration or other setup info as arguments to customize the app.
def create_app(): app = Flask(__name__) app.config['DEBUG'] = True 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 .views import main_blueprint app.register_blueprint(main_blueprint) return app
This example shows a complete Flask app using the application factory pattern. It creates the app inside create_app, sets debug mode, registers a blueprint with a route, and runs the app.
from flask import Flask, Blueprint main_blueprint = Blueprint('main', __name__) @main_blueprint.route('/') def home(): return 'Hello from the factory app!' def create_app(): app = Flask(__name__) app.config['DEBUG'] = True app.register_blueprint(main_blueprint) return app if __name__ == '__main__': app = create_app() app.run()
Use the factory pattern to avoid creating app instances at import time, which helps testing and scaling.
Extensions like Flask-Migrate or Flask-Login often require the app instance, so initialize them inside the factory or use their init_app method.
Remember to register all blueprints and extensions inside the factory function before returning the app.
The application factory pattern creates Flask apps inside a function for flexibility.
It helps manage different configurations and organize code better.
Use it to register blueprints and initialize extensions cleanly.