The application factory pattern helps you create Flask apps in a clean way. It lets you make multiple app instances with different settings easily.
0
0
Application factory pattern preview in Flask
Introduction
When you want to create different versions of your app for testing and production.
When you need to organize your app code better as it grows.
When you want to delay app creation until you have all settings ready.
When you want to register extensions and blueprints in a clean, reusable way.
Syntax
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.
Examples
Simple factory that just creates and returns a Flask app.
Flask
def create_app(): app = Flask(__name__) return app
Factory that loads configuration based on the given name.
Flask
def create_app(config_name): app = Flask(__name__) app.config.from_object(config_name) return app
Factory that initializes extensions and registers blueprints before returning the app.
Flask
def create_app(): app = Flask(__name__) from .extensions import db db.init_app(app) from .routes import main app.register_blueprint(main) return app
Sample Program
This example shows a simple Flask app using the application factory pattern. It creates the app inside create_app, registers a blueprint with a home route, and runs the app.
Flask
from flask import Flask, Blueprint main = Blueprint('main', __name__) @main.route('/') def home(): return 'Hello from the factory app!' def create_app(): app = Flask(__name__) app.register_blueprint(main) return app if __name__ == '__main__': app = create_app() app.run(debug=True)
OutputSuccess
Important Notes
Use the factory pattern to keep your app flexible and testable.
Register extensions and blueprints inside the factory function.
Do not create the app globally; always create it inside the factory.
Summary
The application factory pattern creates Flask apps inside a function.
This helps with configuration, testing, and organizing code.
Use it to register extensions and blueprints cleanly.