The Analogy: The Automobile Assembly Line and Its Build Sheets
An assembly line does not keep one finished car parked in the corner that everybody shares. It keeps the capability to build a car, and it builds one to order the moment a build sheet arrives. Two cars coming off the same line are entirely separate vehicles: adjusting the mirrors on one does nothing to the other, because each was assembled fresh from the same design rather than handed out as references to a single display model. The line is a function that returns a new, complete car; it is not the car.
What makes each car different is its build sheet, and build sheets layer. First the base specification is applied -- standard engine, standard wheels, a default rev limit -- then the ordered trim package overlays its changes on top, perhaps raising the rev limit for the sport trim while leaving the wheels untouched. The same line can therefore build a road car for a customer and a stripped crash-test car for the lab from one design, differing only in the sheets they were fed. There is a discipline to the sheet, though: the line reads only the official, printed specification fields. A lowercase note scribbled in the margin is not part of the spec and the line ignores it entirely, even if it looks like it should matter.
Some parts are shared subassemblies installed into every car -- the infotainment module, say, is one part design fitted to each vehicle. But fitting it is a per-car act: the module is bolted into this car and calibrated to this car's options, and it lives inside the car from then on. The part design is common; the installed, calibrated instance belongs to one specific vehicle and travels with it off the lot.
The failure mode is the single calibration gauge left on the workbench. Because every car's infotainment module is calibrated during install, a lazy technician might read a car's configured rev limit off the shared bench gauge instead of off the car itself. That works until the second car is built: the bench gauge now shows the last car's calibration, and the technician reads the wrong value for the first car. The line's real safeguard is that each car's settings are written into the car, never left only on the shared bench tool. Flask draws this line exactly: the factory function builds a fresh configured app per call, the layered build sheet is configuration loaded from objects then overrides, a shared extension is installed per app with init_app, and the bench-gauge bug is storing per-app state on the extension object instead of on the app.
Syntax or Core Structure
The application factory is a function -- conventionally create_app -- that constructs, configures, and returns a fresh Flask instance. Nothing is created at import time; the app exists only once the factory is called. Because each call returns a new object, the same factory can build a production app and an isolated test app that share no state.
from flask import Flask, jsonify
def create_app(config=None):
app = Flask(__name__)
app.config.update(RATE_LIMIT=100, DEBUG=False)
if config:
app.config.update(config)
@app.get("/limit")
def limit():
return jsonify(limit=app.config["RATE_LIMIT"])
return app
prod = create_app()
test = create_app({"RATE_LIMIT": 5, "TESTING": True})
print("prod:", prod.test_client().get("/limit").get_json())
print("test:", test.test_client().get("/limit").get_json())
print("prod TESTING:", prod.config["TESTING"])
print("test TESTING:", test.config["TESTING"])
Output:
prod: {'limit': 100}
test: {'limit': 5}
prod TESTING: False
test TESTING: True
The factory applies defaults first, then overlays the optional config mapping -- the base build sheet, then the trim overrides. prod and test are independent vehicles: prod keeps the default rate limit of 100 while test overrides it to 5, and each reports its own TESTING value. Note that prod.config["TESTING"] returns False without a KeyError, because Flask seeds a set of standard config keys (including TESTING and DEBUG) with defaults. Routes are registered inside the factory so they close over the app being built, which is why the /limit view reads the correct per-app configuration.
Technical Depth: Configuration Sources and the init_app Pattern
app.config is a dictionary with extra loading methods. Configuration is layered: later loads override earlier ones, so the usual order is defaults, then an environment-specific object, then secrets from the environment. The most important rule is that class- and file-based loaders read only UPPERCASE names.
Where configuration comes from and how it layers
from flask import Flask
class BaseConfig:
DEBUG = False
RATE_LIMIT = 100
PAGE_SIZE = 20
class TestConfig(BaseConfig):
TESTING = True
RATE_LIMIT = 5
app = Flask(__name__)
app.config.from_object(BaseConfig)
print("after base :", app.config["RATE_LIMIT"], app.config["PAGE_SIZE"])
app.config.from_object(TestConfig)
print("after test :", app.config["RATE_LIMIT"], app.config["PAGE_SIZE"], app.config["TESTING"])
app.config.update(RATE_LIMIT=999)
print("after update:", app.config["RATE_LIMIT"])
class Sneaky:
rate_limit = 3
app.config.from_object(Sneaky)
print("lowercase loaded?", "rate_limit" in app.config)
Output:
after base : 100 20
after test : 5 20 True
after update: 999
lowercase loaded? False
TestConfig inherits PAGE_SIZE from BaseConfig (so it stays 20) while overriding RATE_LIMIT to 5, and the later update wins with 999 -- each layer overlays the last. The final line is the trap that catches everyone once: from_object copies only attributes whose names are entirely uppercase, so the lowercase rate_limit is silently ignored and never enters the config at all. A setting that "won't take effect" is very often a lowercase config name.
| Method | Source | Notes |
|---|---|---|
| from_object | a class or import path | reads UPPERCASE attributes only |
| from_pyfile | a .py file on disk | executes it, reads UPPERCASE names |
| from_envvar | env var naming a file | loads the file that variable points to |
| from_prefixed_env | environment variables | loads vars sharing a given prefix |
| from_mapping or update | a dict or keyword args | direct override, wins when applied last |
The init_app pattern
Extensions such as the database layer or a login manager are created once at import time with no app attached, then bound to each app inside the factory with init_app(app). This two-step dance exists precisely because of the factory: the extension object must be importable by blueprint modules before any app exists, yet its real setup -- reading config, registering teardowns -- can only happen once an app is being built. The rule that keeps this safe is that per-app state lives on the app (in app.extensions), never as mutable attributes on the shared extension object, because that one object is reused across every app the factory builds. The real-world example below shows both the correct pattern and the bug that ignores this rule.
Real World Example: A Rate-Limit Extension Bound Per App
Here is a miniature extension in the standard shape: created once at import with no app, bound to each app in the factory with init_app, and storing its per-app state in app.extensions. The factory builds two apps with different limits. The last line deliberately probes the shared extension object to expose the bench-gauge trap.
from flask import Flask, jsonify
class Limiter:
def __init__(self):
self.default = None
def init_app(self, app):
self.default = app.config.get("RATE_LIMIT", 60)
app.extensions["limiter"] = {"limit": self.default}
limiter = Limiter()
def create_app(config=None):
app = Flask(__name__)
app.config.update(RATE_LIMIT=100)
if config:
app.config.update(config)
limiter.init_app(app)
@app.get("/limit")
def show():
return jsonify(limit=app.extensions["limiter"]["limit"])
return app
a = create_app()
b = create_app({"RATE_LIMIT": 5})
print("app a route:", a.test_client().get("/limit").get_json())
print("app b route:", b.test_client().get("/limit").get_json())
print("shared limiter.default:", limiter.default)
Output:
app a route: {'limit': 100}
app b route: {'limit': 5}
shared limiter.default: 5
The Limiter object is created at module load with no app in sight, which is what lets a blueprint import limiter long before any app exists. The real wiring happens in create_app: init_app reads that app's RATE_LIMIT and records the resolved limit in app.extensions["limiter"], a dictionary Flask maintains per app for exactly this purpose. The view then reads its limit back out of app.extensions, so it always reports the configuration of the app it belongs to.
The two route lines prove the per-app storage is correct. App a was built with the default limit of 100 and app b with an override of 5, and each route returns its own app's value. Nothing leaked between them, because the resolved limit was written into each app rather than held in one shared place. This is the pattern every mature Flask extension follows, and swapping Limiter for a real database or cache client changes nothing structural.
Reached for as a template, the shape is worth memorising: a module-level extension instance, an init_app that reads config and registers per-app state and teardowns, and views that pull that state from current_app.extensions rather than from the instance. The factory composes these exactly as the assembly line installs a shared subassembly into each distinct car.
The genuine design flaw is the last line of output. limiter.default is 5, not 100 -- it holds only the most recently built app's value, because init_app overwrote the single shared attribute on each call. That attribute is the calibration gauge left on the workbench. Any code that read limiter.default to make a decision would silently use app b's limit while serving app a, and under a test suite that builds several apps the value would be whatever the last-built app set. The bug is invisible in the common case where only one app is ever created, which is precisely why it survives into projects that later add a second app for testing. The fix is the rule stated above: never store per-app state on the extension object; keep it in app.extensions and read it through current_app.
Common Mistakes
- Creating the app at module level. A global
app = Flask(__name__)runs at import, so tests cannot build an isolated app and import order becomes load-bearing. Build the app insidecreate_appand return it.
- Storing per-app state on the extension object. Mutable attributes on a shared extension instance are overwritten by every app the factory builds. Keep per-app state in
app.extensionsand read it throughcurrent_app.
- Using lowercase config names with
from_object. Only fully-uppercase attributes are loaded; adebugorrate_limitattribute is silently ignored. A setting that never takes effect is usually a lowercase name.
- Reading config at import time. Capturing
app.config[...]into a module global at import freezes the default before the factory applies overrides. Read config insideinit_appor per request, not at module scope.
- Hardcoding secrets in a config class. A
SECRET_KEYcommitted inconfig.pyleaks into version control. Load secrets from the environment withfrom_prefixed_envorfrom_envvar.
- Forgetting to call
init_appin the factory. An imported extension that is never bound looks configured but has no app wiring, andapp.extensionswill lack its entry. Every extension needs itsinit_app(app)call insidecreate_app.
- Registering blueprints or extensions at import time. Doing the wiring outside the factory causes double registration when a second app is built, raising errors or duplicating routes. All composition belongs inside
create_app.
- Loading config layers in the wrong order. Later loads win, so applying defaults after overrides wipes the overrides. Load defaults first, environment-specific config next, and secrets last.
- Leaving
DEBUGon by relying on ambient environment. Branch configuration by an explicit config object per environment rather than trusting a stray environment variable, so production never boots with the interactive debugger enabled.
Best Practices
- Build the app only in
create_app. No module-level app instance; the factory is the single place an app is constructed and wired.
- Layer configuration in a fixed order. Apply a defaults object, then an environment-specific object, then secrets from the environment, so each layer overlays the last predictably.
- Use UPPERCASE config names exclusively. It is the only form the class and file loaders read, and it keeps config keys visually distinct from ordinary attributes.
- Keep secrets out of code. Load
SECRET_KEYand credentials from the environment withfrom_prefixed_envorfrom_envvar; never commit them in a config class.
- Create extensions at module scope and bind with
init_app. This lets blueprints import the extension before any app exists, while real setup happens per app in the factory.
- Store per-app extension state in
app.extensions. Read it throughcurrent_app.extensionsso multiple apps built from one factory never share the wrong values.
- Provide a dedicated testing configuration. A config with
TESTING = Trueplus a fresh app per test gives fully isolated, repeatable tests.
- Register blueprints inside the factory. Explicit
register_blueprintcalls increate_appmake composition visible and let tests build a differently-wired app from the same parts.
Practice Exercises
- Extract a factory. Convert a script with a global
appinto acreate_appfactory, then build a production app and a test app and show they hold independentRATE_LIMITvalues.
- Config hierarchy. Write
BaseConfig,DevConfig, andTestConfigclasses, load one by name in the factory, and demonstrate that a lowercase attribute added to a config class is not loaded.
- Per-app extension. Build a small extension whose
init_apprecords state inapp.extensions. Prove two apps keep separate values through their routes, and that a value stored on the instance itself reflects only the last app built.
- Secret from the environment. Load a value from an environment variable with
from_prefixed_env(orfrom_envvar), show it overriding the default, and confirm the secret never appears in the source.