In simple Flask tutorials, the application instance is created as a global variable at module level: app = Flask(__name__). While fine for prototypes, global application objects cause severe architectural issues in production:
db from app.py, while app.py imports views.The Application Factory Pattern resolves all of these issues by encapsulating app creation inside a factory function, conventionally named create_app().
When using the factory pattern, extensions (like SQLAlchemy, LoginManager, Migrate) are instantiated globally without an app argument. Later, they are bound to the app instance inside create_app() via their .init_app() method:
create_app() Factory Functionrun.py / wsgi.py)Now the entry point is clean and minimal:
With the Application Factory, automated tests can instantiate fresh, disposable app instances backed by an in-memory SQLite database:
create_app)?create_app() rather than at the top of the file?test_app.app_context() provide during unit tests?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Modular Routing with Flask Blueprints | Building JSON APIs with jsonify & Status Codes |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.