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.
Practice
application factory pattern in Flask?Solution
Step 1: Understand the pattern purpose
The application factory pattern creates the Flask app inside a function instead of at the global level.Step 2: Identify benefits
This allows flexible configuration and easier testing by creating multiple app instances with different settings.Final Answer:
To create the Flask app inside a function for flexible configuration -> Option AQuick Check:
Application factory = flexible app creation [OK]
- Thinking it restricts routes to one file
- Believing it disables debugging automatically
- Confusing it with blueprint usage
Solution
Step 1: Check function definition
The factory function must create a Flask instance inside it and return that instance.Step 2: Validate syntax
def create_app():\n app = Flask(__name__)\n return app correctly createsapp = Flask(__name__)and returns it.Final Answer:
def create_app():\n app = Flask(__name__)\n return app -> Option CQuick Check:
Factory returns new Flask instance [OK]
- Defining app globally outside function
- Returning Flask class instead of instance
- Missing parentheses when creating Flask instance
print(app.config['DEBUG']) output?def create_app():
app = Flask(__name__)
app.config.from_mapping(DEBUG=True)
return app
app = create_app()
print(app.config['DEBUG'])Solution
Step 1: Analyze config setting
The factory setsDEBUG=Trueusingapp.config.from_mapping().Step 2: Check printed value
After creating the app, printingapp.config['DEBUG']outputs the value set, which isTrue.Final Answer:
True -> Option BQuick Check:
Config DEBUG set True = True [OK]
- Assuming default DEBUG is False
- Expecting KeyError if not set globally
- Confusing config keys with environment variables
def create_app():
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello'
return app
app = create_app()
app.run()Solution
Step 1: Review app.run() usage
Callingapp.run()directly withoutif __name__ == '__main__'can cause issues when importing.Step 2: Check other code parts
Flask constructor and route decorator are correct; home() returns a string properly.Final Answer:
Calling app.run() outside the main guard -> Option DQuick Check:
Run inside main guard to avoid import issues [OK]
- Ignoring main guard for app.run()
- Thinking route decorator syntax is wrong
- Assuming missing return in home()
Solution
Step 1: Understand configuration loading in factory
The factory should accept a parameter to select configuration and load it properly usingapp.config.from_object().Step 2: Evaluate options
def create_app(config_name): app = Flask(__name__) if config_name == 'dev': app.config.from_object('config.DevConfig') else: app.config.from_object('config.ProdConfig') return app correctly uses a parameter and loads config classes conditionally inside the factory function.Step 3: Identify incorrect options
app = Flask(__name__) if config_name == 'dev': app.config.from_object('config.DevConfig') else: app.config.from_object('config.ProdConfig') defines app globally, breaking factory pattern. Options C and D do not load config properly.Final Answer:
def create_app(config_name): app = Flask(__name__) if config_name == 'dev': app.config.from_object('config.DevConfig') else: app.config.from_object('config.ProdConfig') return app -> Option AQuick Check:
Factory with config param loads correct settings [OK]
- Creating app globally instead of inside factory
- Assigning config directly instead of loading
- Not using parameter to select config
Ready to prove it?
Pass the test and this pattern moves unknown
