The Application Factory Pattern (create_app)
The Application Factory Pattern (create_app)
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:
- 1Circular Import Nightmares: Views import
dbfromapp.py, whileapp.pyimports views. - 2Testing Limitations: You cannot create isolated app instances with different configurations (e.g. SQLite for tests, PostgreSQL for production).
- 3Multiple Instances: Running multiple instances of the same app in a single process is impossible.
The Application Factory Pattern resolves all of these issues by encapsulating app creation inside a factory function, conventionally named create_app().
1. Decoupling Extension Initialization
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:
2. Implementing the create_app() Factory Function
3. The Entry Point (run.py / wsgi.py)
Now the entry point is clean and minimal:
4. Why This Pattern Revolutionizes Testing
With the Application Factory, automated tests can instantiate fresh, disposable app instances backed by an in-memory SQLite database:
Practice Quiz
create_app)?create_app() rather than at the top of the file?test_app.app_context() provide during unit tests?Building JSON APIs with jsonify & Status Codes
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Modular Routing with Flask Blueprints | Building JSON APIs with jsonify & Status Codes |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.