What is Flask's application factory pattern?
Answer
The application factory pattern creates the Flask app inside a function rather than at module level. This solves two problems: circular imports (extensions and blueprints import the app, but the app needs to import them) and testing (create app instances with different configs per test). Create a factory: def create_app(config=None): app = Flask(__name__); app.config.from_object(config or 'config.DefaultConfig'); db.init_app(app); app.register_blueprint(auth_bp); return app. Extensions like Flask-SQLAlchemy support this via db = SQLAlchemy() (without an app) and db.init_app(app). The factory is called in the entry point: app = create_app(). In tests: app = create_app('config.TestingConfig'); client = app.test_client(). This is the recommended pattern for any Flask app beyond a simple script.
Previous
How does SQLAlchemy async work with FastAPI?
Next
How do you implement background tasks in FastAPI?
More FastAPI / Flask Questions
View all →- Intermediate How do you implement JWT authentication in FastAPI?
- Intermediate How does SQLAlchemy async work with FastAPI?
- Intermediate How do you implement background tasks in FastAPI?
- Intermediate What is Pydantic v2 and what changed from v1?
- Intermediate How do you implement middleware in FastAPI?