Application Factory (Flask)
An application factory is a function (commonly named create_app) that builds and returns a configured Flask app. It avoids module-level globals, makes testing easier, and lets you create app instances with different configs.
Flask
Instead of creating app = Flask(__name__) at the top of a module, you wrap that logic in a function. Inside it you create the app, load config, initialize extensions with init_app(app), register Blueprints, and return the app. The server or tests call the factory to get an instance.
This pattern solves real problems: it lets your test suite spin up a fresh app with a test database, prevents circular imports between your app and extensions, and supports running the same code with development, testing, and production settings.
With a factory, extensions are created once at import time as bare objects (db = SQLAlchemy()) and bound to the app inside the factory via db.init_app(app), so they are not tied to a single global application.
Syntax
def create_app(config=None):
app = Flask(__name__)
return appExamples
Python
from flask import Flask
from .extensions import db
def create_app():
app = Flask(__name__)
app.config.from_object("config.Dev")
db.init_app(app)
from .views import main
app.register_blueprint(main)
return app