An application factory is a callable that creates and configures an application instance when invoked. In Flask, it replaces direct app creation with a create_app() function, giving the application more control over initialization and making it easier for external modules to use. section 7.3.1
A practical refactoring moves the Flask application into an app package. The package holds templates and static assets, while myblog.py becomes a small entry point that imports create_app() and calls it. section 7.3.1
The pattern supports a gradual move toward clearer application architecture:
- Keep routes and rendering behavior inside the factory initially, preserving the existing page while changing the structure. section 7.3.1
- As the application grows, move related routes into a package namespace and register its Blueprint from the factory. section 7.4.2
Minimal factory entry point
from flask import Flask\n\ndef create_app():\n app = Flask(__name__)\n with app.app_context():\n from . import intro\n app.register_blueprint(intro.intro_bp)\n return app
