Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 72 ยท Structure and Configuration

The Application Factory

Learn the Flask application factory pattern: write create_app, set up extensions with init_app, give tests their own config and run several apps side by side.

In the earliest lessons you wrote app = Flask(__name__) at the top of a file and decorated functions with @app.route. That is perfect for a single file. As soon as your project grows into several modules, the global app starts to hurt. Other modules must import it, but it needs to import them to register routes, so you get circular imports. Tests cannot get a fresh app with different settings, because there is only one, created the moment the module is imported.

The standard cure is the application factory: a function, conventionally named create_app, that builds and returns a configured Flask object each time you call it. This lesson shows how to write one, how extensions fit in with init_app, and how the same pattern gives tests a clean app every time.

The idea

flowchart TD
    A["create_app(config)"] --> B["app = Flask(__name__)"]
    B --> C["load default config,<br/>then apply overrides"]
    C --> D["extensions.init_app(app)"]
    D --> E["register blueprints<br/>and error handlers"]
    E --> F["return app"]

A factory assembles the app step by step, so each caller can decide the settings.

Nothing about your routes, templates or extensions changes. What changes is when the app object comes into existence: not at import time, but when somebody asks for it. That small shift gives you three things:

  • Configuration per use. Development, testing and production each call the factory with different settings.
  • Isolation. Every call returns an independent app, with its own config, its own URL map and its own extension state.
  • No import-time side effects. Importing your package does not connect to a database or read files.

A first factory

Here is a factory that accepts an optional dictionary of overrides. Inside views, code reaches the running app through current_app instead of a global variable. Two apps are built from the same function, and they stay completely separate.

Python One factory, two independent apps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line proves the isolation: changing the staging app's config does not touch the dev app. Setting TESTING to True is also visible through current_app.testing.

A few details about the code:

  • Defaults first, overrides second. from_mapping sets safe defaults; the optional argument replaces some of them. Later lessons add from_object, environment variables and an instance folder to this ladder. See Configuration and Environments.
  • Routes are registered inside the factory. With a single file that is fine. In a bigger project you move them into blueprints and call app.register_blueprint(...) here, covered in Blueprints.
  • current_app is a proxy that points to whichever app is handling the current request. It is how modules outside the factory read config without importing the app. Hooks, Application Context and g explains how the application context makes that work.

Extensions and init_app

Flask extensions such as Flask-SQLAlchemy, Flask-Migrate and Flask-Login follow one convention. You create the extension object at module level without an app, and bind it later with init_app(app) inside the factory. Because the object exists at import time, models and other modules can import it, and because it is bound lazily, the factory still decides the configuration.

A typical package looks like this:

TEXT
myapp/
    __init__.py       # create_app()
    extensions.py     # db = SQLAlchemy(), migrate = Migrate(), ...
    models.py         # from .extensions import db
    blog/
        __init__.py   # blueprint
        routes.py
    templates/
    static/
wsgi.py               # from myapp import create_app; app = create_app()

extensions.py holds only the unbound objects:

Python
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

db = SQLAlchemy()
migrate = Migrate()

and the factory wires them up:

Python
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object("myapp.config.Default")
    if config:
        app.config.update(config)

    db.init_app(app)
    migrate.init_app(app, db)

    from .blog import bp as blog_bp
    app.register_blueprint(blog_bp)
    return app

Notice that models.py can do from .extensions import db with no circularity: extensions.py imports nothing from your app.

The one db object can serve many apps. The following example puts the module layout into one file, with comments marking the files. It builds two apps that each get their own in-memory database, then shows what happens when you use db without an app context.

Python One db object, two apps, two databases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

flowchart LR
    DB(["db = SQLAlchemy()<br/>one shared object"])
    A1["app 1"] --- E1[("engine 1")]
    A2["app 2"] --- E2[("engine 2")]
    DB -. "init_app(app 1)" .-> A1
    DB -. "init_app(app 2)" .-> A2

The extension object is shared; the state it needs (engine, session) is stored per app.

The extension asks "which app am I serving right now?" and answers by looking at the application context. Outside one, it has no idea which database to use, so it raises RuntimeError: Working outside of application context. Views get a context automatically. In scripts, shells and tests you open one yourself with with app.app_context():.

If a factory feels like ceremony for a 50-line project, skip it. But start using one before you add a second blueprint, a database or tests. Converting later is only a few minutes of work, and it is much easier than untangling circular imports.

Giving tests their own configuration

The biggest day-to-day benefit shows up in tests. Each test can build a brand new app with exactly the settings it needs, with no state left over from the previous test. The usual convention is a test_config parameter that is applied after the defaults. Setting TESTING = True turns on Flask's testing behaviour: exceptions inside views propagate to the test instead of becoming generic error pages, so you see real tracebacks.

The next example writes pytest-style test functions and calls them by hand, since a test runner is not available in the page. A real project would let pytest discover them and pass the client as a fixture, which Testing Flask Apps with pytest shows.

Python A fresh app per test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second test lowers MAX_ITEMS to 1 without touching any file or global, and the third starts with an empty session even though an earlier test added an item. That independence is what makes a test suite trustworthy.

Running a factory app

The flask command knows about factories. It looks in the module you name for a variable called app or application, and failing that for a function called create_app or make_app, which it calls with no arguments:

Terminal
flask --app myapp run --debug

For production, WSGI servers need an app object, not a function. The common solution is a tiny wsgi.py that calls the factory once:

Python
# wsgi.py
from myapp import create_app

app = create_app()

and then gunicorn wsgi:app serves it. Gunicorn can also call a factory itself with "myapp:create_app()". Deployment details are in Deployment.

Common mistakes

  • Doing work at import time. Opening database connections or reading config at module level defeats the pattern. Put it inside create_app.
  • Importing the app object into other modules. There is no global app any more. Use current_app inside requests, or pass the app explicitly.
  • Calling db.init_app(app) twice on the same app, or forgetting it entirely. The latter shows up as an error saying the current Flask app is not registered with this SQLAlchemy instance.
  • Importing blueprints at the top of __init__.py when they import models that import the factory module. Import them inside create_app, just before registering, to dodge cycles.
  • Sharing mutable module-level state (lists, dicts, caches) between apps. Each call to the factory should be able to start from nothing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main reason Flask projects use an application factory?

    A factory delays creating the app until you ask for it, so each caller (development, tests, production) can choose its own configuration and get an isolated app.
  2. 2. Where should the line db = SQLAlchemy() live in a factory-based project?

    Create the extension object at import time so models can import it, then bind it to an app with db.init_app(app) inside the factory.
  3. 3. A view needs a config value, but there is no global app to import. What do you use?

    current_app is a proxy to the app handling the current request or application context.
  4. 4. You run db.session.scalars(db.select(Item)) in a plain script and get RuntimeError: Working outside of application context. What is the fix?

    The extension finds the right database through the application context. Outside a request you must push one yourself.
  5. 5. How does the flask command find a factory when you run flask --app myapp run?

    Flask's CLI supports factories out of the box: without an app variable it calls create_app() or make_app() in the named module.

Summary

  • An application factory is a function, usually create_app, that builds and returns a configured Flask app each time it is called.
  • Create extensions at module level without an app and bind them in the factory with init_app(app); this avoids circular imports.
  • Read config and the running app through current_app, not through an imported global.
  • Extension state is stored per app, so one db object can serve several apps; outside a request you need app.app_context().
  • Tests call the factory with a test config and get a fresh, isolated app every time.
  • flask --app myapp run finds create_app by itself; production servers use a small wsgi.py that calls the factory.

Next: Blueprints, splitting a growing app into reusable pieces.