0
0
Flaskframework~7 mins

Application factory pattern deep dive in Flask

Choose your learning style9 modes available
Introduction

The application factory pattern helps create Flask apps in a flexible way. It lets you make multiple app instances with different settings easily.

When you want to create multiple Flask apps with different configurations in the same project.
When you need to write tests that require fresh app instances for isolation.
When your app needs to load different settings for development, testing, and production.
When you want to organize your app code cleanly and avoid global state.
When you plan to use extensions that require initialization after app creation.
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
Basic factory that creates and returns a Flask app with default settings.
Flask
def create_app():
    app = Flask(__name__)
    return app
Factory that loads configuration from a given config class or object.
Flask
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_name)
    return app
Factory that initializes extensions and registers blueprints after creating the app.
Flask
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
Sample Program

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.

Flask
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)
OutputSuccess
Important Notes

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.

Summary

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.