Testing and Serving in Production

Testing and Serving in Production in Flask: Before a new airliner ever carries a passenger, the manufacturer tests it in stages of rising fidelity.

The Analogy: The Aircraft Test Rig and the Flight Line

Before a new airliner ever carries a passenger, the manufacturer tests it in stages of rising fidelity. An engineer bench-tests a single hydraulic actuator on a workbench rig. Then whole systems are wired into a grounded "iron bird" -- a skeletal airframe with the real hydraulics, cabling and controls laid out so they can be exercised together without leaving the hangar. Then the complete aircraft is run up and down the taxiway under its own power. Only after all of that does a trained crew take it up for a handful of test flights. Each stage is faster, cheaper and safer than the one after it, and each catches a different class of fault.

The whole point of the grounded rigs is that you find almost every fault without leaving the ground. A cracked bracket shows up on the bench in minutes; a mis-wired warning lamp shows up on the iron bird in an afternoon. You do not go looking for either by taking off with a full cabin and seeing what happens. So the cheap tests are the ones the team runs constantly, all day, and the expensive test flight is reserved for the few things that only a real flight can prove. Inverting that order -- skipping the rigs and trusting the flight -- is how you turn a five-minute fix into an emergency.

When the aircraft finally enters service, the airline does not fly its whole schedule on one plane. It operates many identical airframes of the same type, each fuelled and stocked on its own, so one aircraft in maintenance never grounds the fleet. A control tower and ground dispatch handle everything the cockpit should not: sequencing traffic, screening passengers at the gate, buffering slow or confused arrivals so they do not block the runway, and relaying each inbound flight's true origin. And nothing pushes back from the gate until a firm go/no-go check confirms the aircraft is actually fit to fly.

One low-cost operator did almost none of this. It "tested" by taxiing a passenger aircraft up and down with travellers already aboard, so every fault was discovered in front of paying customers. It ran the entire timetable on a single overworked airframe, so one slow turnaround stranded everyone at once. It left the prototype's open diagnostic panel -- the one that lets an engineer command any system directly -- wired live in the cabin where any passenger could reach it. And its departure board was hard-wired to read "ready" no matter what, so dispatch kept loading people onto an aircraft with a dead engine. Every one of those is a specific, avoidable production mistake, and each maps exactly onto a way a Flask deployment goes wrong.


Syntax or Core Structure

The equivalent of the iron bird is Flask's test client: it dispatches a real request through the entire application stack -- routing, hooks, the view, error handlers, JSON serialisation -- entirely in-process, with no socket and no running server. The factory function that builds the app is what makes this cheap: each test constructs its own app with its own configuration, so tests never share state. A single grounded exercise of an endpoint looks like this:

from flask import Flask, request, jsonify


def create_app(config=None):
    app = Flask(__name__)
    app.config.update(config or {})

    @app.post("/api/products")
    def create_product():
        data = request.get_json(silent=True) or {}
        if float(data.get("price", 0)) < 0:
            return jsonify(error="bad_price", fields=["price"]), 400
        return jsonify(sku=data.get("sku"), created=True), 201

    return app


app = create_app({"TESTING": True})
client = app.test_client()

ok = client.post("/api/products", json={"sku": "HEX-4", "price": "4.50"})
print("create:", ok.status_code, ok.get_json())

bad = client.post("/api/products", json={"sku": "X", "price": "-1"})
print("reject:", bad.status_code, bad.get_json())

Output:

create: 201 {'created': True, 'sku': 'HEX-4'}
reject: 400 {'error': 'bad_price', 'fields': ['price']}

Two habits are already visible. Assert on the status code, not only the body: an endpoint that quietly returns 200 instead of 201 has broken its contract even when the payload looks right. And notice the JSON keys come back alphabetically (created before sku) -- Flask sorts them by default, which is what makes an exact-output assertion stable across runs.


Technical Depth: Testing at the Right Level, and Seeding State

Choose the cheapest rig that proves the point

Like the aircraft team, you have tools of increasing fidelity and cost. Pick the lowest one that can prove the thing you care about, and push logic down to where it can be tested without HTTP at all:

LevelToolUse it for
Pure functionplain pytest, no FlaskBusiness rules, calculations, parsing
Request contexttest_request_contextHelpers that read request, session, or g
Endpointtest_clientStatus codes, contracts, auth guards
Full stacklive server plus a browser driverA few critical user journeys only

A pricing rule tested as a plain function runs in a millisecond; the same rule tested only through an endpoint is slower, flakier, and tells you less about what actually failed.

A request context without a running view

Some helpers read request or g and so cannot be called from a plain test. test_request_context pushes a fake request context so they work outside any view:

from flask import Flask, request

app = Flask(__name__)


def parse_search_args():
    return {"q": request.args.get("q", ""),
            "page": int(request.args.get("page", 1))}


with app.test_request_context("/search?q=drill&page=2"):
    print(parse_search_args())

with app.test_request_context("/search"):
    print(parse_search_args())

Output:

{'q': 'drill', 'page': 2}
{'q': '', 'page': 1}

Use test_request_context for helpers and test_client for endpoints; reaching for a full browser driver to test a query-string parser is flying the airliner to check a bracket.

Seeding the session so you can test what is behind the gate

Testing a protected endpoint by driving the login form on every test is slow and couples the test to the login page. session_transaction lets a test write directly into the signed session cookie, so you can arrive at a guarded route already authenticated:

from flask import Flask, session, jsonify

app = Flask(__name__)
app.secret_key = "test-key"


@app.get("/me")
def me():
    uid = session.get("user_id")
    if uid is None:
        return jsonify(error="login_required"), 401
    return jsonify(user_id=uid)


client = app.test_client()
print("no session:", client.get("/me").status_code)

with client.session_transaction() as sess:
    sess["user_id"] = 7
print("seeded:", client.get("/me").get_json())

Output:

no session: 401
seeded: {'user_id': 7}

The first request has no session and is correctly rejected with 401; after seeding user_id into the session, the same client is treated as logged in. This is the test-only shortcut past the login form, and it works precisely because the test client holds and re-sends the cookie the way a browser does.


Real World Example: Serving the App on a Fleet, and the Header You Must Not Trust

In production, app.run() is the single passenger plane taxiing with travellers aboard: it is a development server, single-threaded by default, and never meant for real load. You run the app under a proper WSGI server that operates a fleet of identical worker processes instead:

gunicorn --workers 4 \
         --bind 127.0.0.1:8000 \
         --timeout 30 \
         --access-logfile - \
         "myapp:create_app()"

Gunicorn forks worker processes, and because it calls your factory inside each worker, every worker gets its own independent copy of the app -- the fuelled-and-stocked airframe. A common starting point is (2 * cpu_cores) + 1 workers, then measure. Two consequences follow directly from there being many processes: in-memory state is per-worker, so a module-level dict used as a cache gives different answers depending on which worker served the request (use Redis or the database), and blocking work occupies a whole worker, so a thirty-second report ties up one of your four airframes entirely (push long jobs to a queue such as Celery or RQ). The app below is assembled by a factory with real config classes, a health endpoint dispatch can trust, and the proxy shim discussed after the output:

from flask import Flask, jsonify, request
from werkzeug.middleware.proxy_fix import ProxyFix


class BaseConfig:
    pass


class TestingConfig(BaseConfig):
    TESTING = True
    SESSION_COOKIE_SECURE = False


class ProductionConfig(BaseConfig):
    TESTING = False
    SESSION_COOKIE_SECURE = True
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = "Lax"


DEPENDENCY = {"up": True}          # stands in for a database, cache, ...


def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)

    @app.get("/healthz")
    def healthz():
        if not DEPENDENCY["up"]:
            return jsonify(status="degraded"), 503
        return jsonify(status="ok"), 200

    @app.get("/whereami")
    def whereami():
        return jsonify(ip=request.remote_addr, scheme=request.scheme)

    return app

prod = create_app(ProductionConfig)
print("prod secure cookie:", prod.config["SESSION_COOKIE_SECURE"])
print("test secure cookie:", create_app(TestingConfig).config["SESSION_COOKIE_SECURE"])

client = prod.test_client()
print("healthy:", client.get("/healthz").status_code, client.get("/healthz").get_json())

DEPENDENCY["up"] = False
print("degraded:", client.get("/healthz").status_code, client.get("/healthz").get_json())
DEPENDENCY["up"] = True

seen = client.get("/whereami", headers={"X-Forwarded-For": "203.0.113.9",
                                        "X-Forwarded-Proto": "https"})
print("client sees:", seen.get_json())

Output:

prod secure cookie: True
test secure cookie: False
healthy: 200 {'status': 'ok'}
degraded: 503 {'status': 'degraded'}
client sees: {'ip': '203.0.113.9', 'scheme': 'https'}

The run proves the two production disciplines that matter most here. First, the same factory yields different security postures purely from the config class it is handed: ProductionConfig turns on SESSION_COOKIE_SECURE while TestingConfig leaves it off, so the environment difference lives in one object rather than scattered if statements. Second, the health endpoint returns 200 while the dependency is up and flips to 503 the moment it goes down. That 503 is the entire point: it is the go/no-go check that tells the load balancer to stop routing to this instance, the opposite of a departure board hard-wired to read "ready."

In front of the workers sits a reverse proxy -- Nginx or your platform's load balancer -- doing the control tower's job, which is everything the worker should not: terminating TLS, serving static files from disk, buffering slow clients so they do not tie up a worker, and enforcing size limits. The full pushback checklist:

ItemRequirement
ServerGunicorn or uWSGI, never app.run()
Debugdebug=False; the interactive debugger must be unreachable
SECRET_KEYRandom, from the environment, never in Git
Session cookiesSecure, HttpOnly, SameSite all set
Migrationsflask db upgrade as a deploy step, never create_all
ErrorsCentral handlers returning generic messages
LoggingStructured, to stdout, with credentials redacted
Health checkA cheap endpoint the load balancer can poll
DependenciesPinned in a lock file

The proxy creates one subtlety the code has to handle. Behind it, request.remote_addr is the proxy's own address and request.scheme reads http, which breaks IP logging, rate limiting, and url_for(_external=True). ProxyFix reads the X-Forwarded-For and X-Forwarded-Proto headers the proxy sets and restores the real values -- the run shows the app correctly reporting 203.0.113.9 and https once those headers arrive.

That restoration is also this design's genuine flaw, because ProxyFix trusts a client-supplied header. The x_for=1 argument means "believe exactly one hop of X-Forwarded-For," and the run proves the app now reports whatever that header says. If this app is ever reachable without the intended proxy in front, or sits behind a different number of proxies than the 1 configured, any client can send their own X-Forwarded-For and forge request.remote_addr -- poisoning audit logs and letting an attacker slip past, or frame someone else in, IP-based rate limiting. The fix is to enable ProxyFix only when a proxy you control is actually in front, set the hop count to match the real topology exactly, ensure that edge strips any inbound X-Forwarded-* from clients, and never treat remote_addr as trustworthy for a security decision until that chain is verified.


Common Mistakes

  1. Serving with app.run() or debug=True in production. The built-in server is single-threaded and for development only, and a reachable interactive debugger is remote code execution. Serve under Gunicorn or uWSGI with debug=False.
  1. Discovering faults in production instead of on a rig. Relying on the live site to surface bugs is taxiing with passengers aboard. Write test_client tests that run on every save so most faults never reach a user.
  1. Asserting on the body but not the status code. A test that checks the payload while the endpoint quietly returns 200 instead of 201 passes with the contract broken. Assert the status code every time.
  1. Testing everything through the endpoint. Driving a full request to exercise a parsing rule is slow and flaky and tells you little. Push logic into pure functions and test those directly.
  1. Running a single worker, or sizing by guesswork. One blocking request then stalls every user at once. Run a fleet of workers, start near (2 * cpu_cores) + 1, and size by measurement.
  1. Keeping state in a module-level dict. With multiple workers that memory is per-process, so a cache or counter gives different answers depending on who served the request. Put shared state in Redis or the database.
  1. Doing long, blocking work inside a request. A thirty-second report ties up a whole worker for its duration. Offload long jobs to a queue such as Celery or RQ and return immediately.
  1. A health check that always returns 200. It tells the load balancer to keep routing traffic to a broken instance. Check the real dependencies and return 503 when one is down.
  1. Enabling ProxyFix without a trusted proxy in front. It trusts X-Forwarded-For, so a client that can reach the app directly forges its own remote_addr. Enable it only behind a proxy you control, with the hop count set to the real topology.

Best Practices

  • Build the app with a factory so each test gets its own configured instance, and select environment behaviour with config classes rather than conditionals scattered through the code.
  • Run the cheapest rig that proves the point: pure functions in plain pytest, test_request_context for helpers, test_client for endpoints, and a browser driver for only a handful of critical journeys.
  • Assert on the status code and the response contract, not just the body, so a wrong status can never pass silently.
  • Seed authentication in tests with session_transaction instead of driving the login form on every test.
  • Serve under Gunicorn or uWSGI with debug=False, and size the worker count by measurement rather than by guessing.
  • Assume nothing is shared between workers: keep shared state in Redis or the database, and move long or blocking work to a queue.
  • Put a reverse proxy in front for TLS, static files, buffering, and limits, and enable ProxyFix only behind a proxy you control with hop counts set to the real topology.
  • Expose a /healthz that checks real dependencies and returns 503 when degraded, and run flask db upgrade as a deploy step instead of create_all.

Practice Exercises

  1. Write two test_client tests for the products endpoint without starting a server: one asserting 201 and the returned sku for a valid POST, and one asserting 400 and that "price" appears in the fields list when the price is negative.
  1. Add a /readyz endpoint separate from /healthz, so liveness (the process is up) and readiness (dependencies are up and migrations applied) are reported independently. Explain in a comment when a load balancer should consult each.
  1. Take the module-level DEPENDENCY dict and describe precisely what would break if its "up" state were cached in a module-level variable across four Gunicorn workers, then rewrite the check so every request re-reads the real dependency.
  1. Harden the ProxyFix configuration for an edge that adds exactly one X-Forwarded-For hop: set x_for correctly, then use test_client to send an extra client-supplied X-Forwarded-For value and show that it does not override the trusted remote_addr.