0
0
Flaskframework~5 mins

Application factory pattern 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 different versions of your app for testing and production.
When you need to delay app creation until some setup is done.
When you want to organize your app code better by separating configuration and app creation.
When you plan to use extensions that require the app instance during initialization.
When you want to write reusable blueprints or components that can be added to any app instance.
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 each time it is called.

You can pass configuration or other setup info as arguments to customize the app.

Examples
A simple factory that creates an app with debug mode on.
Flask
def create_app():
    app = Flask(__name__)
    app.config['DEBUG'] = True
    return app
Factory that loads configuration from a config class or file name.
Flask
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_name)
    return app
Factory that registers a blueprint to organize routes.
Flask
def create_app():
    app = Flask(__name__)
    from .views import main_blueprint
    app.register_blueprint(main_blueprint)
    return app
Sample Program

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.

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

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.

Summary

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.