flask · Architecture

Flask: how the system is designed

Created · run_mwili1rx3922a7e6ac6b5241 · github.com/pallets/flask @ main · commit 49943b5a9441 · model claude-opus-5-5

How the Flask web framework is put together: how a request travels through it, the command line that loads and serves an application, the configuration and session design, the example applications shipped beside it, and how a release reaches PyPI.

24Python files in src/flask
32entry points
29default config keys
10built-in signals
0outbound calls at run time

1. What the system is

Flask is a toolkit for building websites and web services in Python. A programmer imports it, writes a few functions that say what each web address should return, and Flask takes care of the plumbing in between: reading what the browser asked for, finding the right function, remembering a visitor between page loads, and sending the answer back. It is not a website or a service in its own right. Nothing in this repository runs on a server for anyone to visit. It is a library that other people's applications are built from, published on PyPI so anyone can install it.

In engineering terms, Flask is a Python web framework library (version 3.2.0.dev, requires Python 3.11 or later), not a deployed service: it is packaged with flit_core and published to PyPI, and the repository deploys nothing itself (pyproject.toml). It speaks WSGI, the standard interface between Python web servers and applications, and is built on 6 runtime dependencies: blinker>=1.9.0, click>=8.1.3, itsdangerous>=2.2.0, jinja2>=3.1.2, markupsafe>=2.1.1, werkzeug>=3.1.0; with 2 optional extras: async (asgiref>=3.2) and dotenv (python-dotenv). Werkzeug supplies the HTTP request, response and routing machinery, Jinja the templates, Click the flask command line, itsdangerous the cookie signing and Blinker the signals.

The code lives in src/flask: 24 Python files, 18 in src/flask itself, 3 in src/flask/sansio and 3 in src/flask/json. The sansio layer holds the parts of the application and blueprint objects that do no I/O; the classes in src/flask/app.py and src/flask/blueprints.py subclass them and add WSGI, file serving and request handling (section 4). Beside the library the repository ships three example applications under examples/ (a tutorial blog on SQLite, a JavaScript fetch demo, and a Celery task demo on Redis), a test suite under tests/, the documentation sources under docs/, and five GitHub Actions workflows that test, lint and publish the package.

The actors

What the system is for, in one line: to let the application developer turn a set of Python functions into a working web application with as little framework as possible, leaving the choice of database, authentication, forms and hosting to them.

Engineering standards

Engineering standards: 8/10, Good

Good. The score rests on 48 test files against 35 source files run in CI across an 11-job matrix plus strict mypy, with ruff lint and format, codespell and pre-commit hooks gating every pull request, SHA-pinned actions and a committed uv.lock, 0 TODO markers and a deliberate sansio layer. It is held below 9 by src/flask/app.py at 1,686 lines and src/flask/cli.py at 1,126, 7 functions over 100 lines, two dead helpers and a duplicated test (section 17), and a devcontainer whose setup script installs requirements/dev.txt, which does not exist. The technical assessment gives the reasoning per criterion.

RatingScaleScore
Engineering standards8/10 Good
Security8/10 Good
Configuration and secrets7/10 Good
Data and persistence7/10 Good
Error handling and resilience8/10 Good
Availability and recovery7/10 Good
Performance and scale6/10 Fair
Each rating is reasoned in the section it names; 6 or below is carried into the risk register.

2. Business process

Flask serves three journeys. Two of them happen outside this repository, in the applications people build with it: a developer building an application, and that application serving its visitors. The third happens here: the maintainers releasing a new version. Each is told below as the steps a person taking part would recognise, not as the code that carries them out. The code path behind the second journey is drawn in sections 5 and 6, and the release pipeline in section 10.

Build an application

The person here is the application developer. The tutorial blog under examples/tutorial/flaskr/ is the repository's own worked example of this journey from start to finish.

  1. Create the application. The developer makes one application object, usually inside a factory so tests can make a fresh one. The tutorial does this in examples/tutorial/flaskr/__init__.py and gives it an instance folder for files that belong to one installation and are not committed.examples/tutorial/flaskr/__init__.py
  2. Configure it. Settings such as the secret key and the database location are given defaults, then overridden from a file in the instance folder, from environment variables or from a test's own settings. The tutorial ships SECRET_KEY as "dev" and expects a real deployment to override it from instance/config.py. Configuration is covered in section 9.examples/tutorial/flaskr/__init__.py
  3. Say what each address returns. The developer writes a function per page or API call and tells Flask which web address and which HTTP methods it answers. A single page can be added directly to the application, as the tutorial's hello page is.examples/tutorial/flaskr/__init__.py
  4. Group related pages into blueprints. Pages that belong together (the tutorial's sign-up, log-in and log-out pages, and its blog pages) are written as a blueprint and registered on the application in one step, so a larger application is assembled from parts.examples/tutorial/flaskr/auth.py, examples/tutorial/flaskr/blog.py
  5. Add commands and extensions. Housekeeping jobs become flask subcommands (the tutorial's command that creates its database), and third-party extensions attach themselves to the application for databases, forms, login and so on.examples/tutorial/flaskr/db.py
  6. Try it and test it. The developer runs flask run to serve the application on their own machine (127.0.0.1:5000 by default, for development only), and writes tests that call pages through Flask's test client without starting a server.examples/tutorial/tests/
  7. Put it into production. The developer hands the finished application to a WSGI server of their choosing. This step leaves Flask: the repository documents several servers under docs/deploying/ but holds no deployment of its own.docs/deploying/

Serve a request

The person here is the end user, a visitor to an application built with Flask. From their side this is simply asking for a page and getting one back, with the site remembering who they are between visits.

  1. The visitor asks for an address. Their browser or API client sends a request. The WSGI server that hosts the application accepts the connection and hands the request to the application.
  2. The application finds who answers it. Flask matches the address and method against the routes the developer declared. An address nobody declared becomes a "not found" answer, and a known address asked with the wrong method becomes "method not allowed".
  3. It recognises the visitor. On every request, whether or not the page uses it, Flask reads the visitor's session cookie, checks its signature against the application's secret key, and restores whatever the application remembered about them, such as the tutorial's logged-in user. A cookie that was tampered with or has expired is treated as no session at all.
  4. The application's own checks run. Anything the developer asked to happen before every page (loading the current user, refusing a visitor who is not logged in) runs first and may answer on the page's behalf.
  5. The page is produced. The developer's function builds the answer: an HTML page from a template, JSON for a script, a file, or a redirect elsewhere.
  6. The answer goes back with the visitor's memory. Flask turns what the function returned into a proper HTTP response, applies any after-page adjustments, and, if the session changed, sends back a new signed cookie. The cookie is signed, not encrypted, so the visitor can read what is in it but cannot change it.
  7. Something goes wrong. A known problem (a page the visitor may not see, a bad form) becomes the matching error page, using the developer's own error pages where they defined them. An unexpected failure is written to the log and the visitor gets a generic "internal server error" page. Either way, clean-up such as closing the tutorial's database connection still happens.

Release a version

The people here are the Pallets maintainers and contributors. This is the only journey the repository carries out itself, through its GitHub Actions workflows.

  1. A change is proposed. A contributor opens a pull request against the repository..github/workflows/tests.yaml, .github/workflows/pre-commit.yaml
  2. The checks run. The tests run across an 11-job matrix (Python 3.11 to 3.15, free-threaded 3.14t, PyPy, Windows, macOS, and the oldest and newest supported versions of the dependencies), a separate job type-checks the code with mypy, and pre-commit runs ruff lint and format, the lockfile check, codespell and housekeeping hooks. A change that touches a YAML file, the workflows included, is also audited by zizmor..github/workflows/tests.yaml, .github/workflows/pre-commit.yaml, .github/workflows/zizmor.yaml
  3. A maintainer merges it. Reviewed changes land on the main or stable branch, where the same checks run again.
  4. A maintainer tags the release. Pushing a version tag is the single act that starts a release..github/workflows/publish.yaml
  5. The package is built once. The publish workflow builds the source and wheel distributions with a reproducible timestamp and stores them as one artifact, so what is released is exactly what was built..github/workflows/publish.yaml
  6. A draft GitHub release is created. The built files are attached to a GitHub release for the tag, created as a draft..github/workflows/publish.yaml
  7. The version reaches PyPI. In the protected "publish" environment, the same files are uploaded to PyPI through trusted publishing, with no stored password. From that moment every developer running pip install Flask can receive the new version..github/workflows/publish.yaml

Alongside these, one housekeeping job runs on its own: a daily schedule locks closed issues, pull requests and discussions that have had no activity for 14 days, so new reports start fresh rather than reviving old threads (.github/workflows/lock.yaml).

3. Entry points

Flask is a library, so most of the ways work enters it are ways a developer's own code or a WSGI server hands work to it, not routes the repository serves itself. There are 32 entry points: 12 in the library and 20 in the three example applications (tutorial 9, javascript 3, celery 8).

In the library, work arrives from three directions. A command line: the flask console script declared in pyproject.toml and python -m flask both reach main, which hands off to the FlaskGroup command group with its 3 built-in CLI commands, run, shell and routes, plus further commands loaded from the flask.commands entry-point group. A WSGI server: it calls the application object itself through __call__, which is where every production request enters, while run starts the development server for local use. The static-file routes: when a static folder is configured, the application and each blueprint register a /static/<path:filename> rule served by send_static_file. Tests enter through test_client and test_cli_runner, which drive the same request and command paths without a server or a shell.

The examples add HTTP routes, one Click command and three Celery tasks. The tutorial's auth views sit under the /auth blueprint prefix and the celery example's task views under /tasks; the URLs below include those prefixes. The javascript example's index carries two route decorators on one function, and each is a separate way in, so each has a row.

The evidence scan matched 445 lines across 37 files. Most of those are test fixtures under tests/ (routes, error handlers and teardown hooks registered on throwaway apps inside test functions) and usage examples inside docstrings, such as the @app.route("/") samples in src/flask/sansio/scaffold.py and src/flask/ctx.py. Neither is a way work enters the shipped code, so neither is rowed. Library hook decorators such as before_request and errorhandler are registration points that the request path calls into, not entry points, and are covered in sections 5 and 13. CI triggers (pull request, push, tag and the daily cron) are how work enters the repository's automation rather than the code, and are listed with the workflows in section 10.

Entry points 32 rows
PartKindTriggerDeclared atHandlerWhat it does
LibraryConsole scriptflaskpyproject.toml:82, src/flask/cli.py:1121mainRuns the module-level FlaskGroup named flask, which parses the command line, loads the application and dispatches to the chosen command.
LibraryModule runpython -m flasksrc/flask/__main__.py:3mainThe package's __main__ module imports the same function from cli.py and calls it, so this behaves exactly like the console script.
LibraryCLI commandflask runsrc/flask/cli.py:881run_commandLoads the application and serves it with Werkzeug's development server, turning the reloader and debugger on when debug mode is set. Its docstring states it is for development only.
LibraryCLI commandflask shellsrc/flask/cli.py:998shell_commandOpens an interactive Python shell inside the application context, first running the file named by PYTHONSTARTUP and adding the app's shell-context variables.
LibraryCLI commandflask routessrc/flask/cli.py:1047routes_commandPrints every registered URL rule with its endpoint, methods and, where used, host or subdomain, sorted by endpoint unless another key is chosen. HEAD and OPTIONS are hidden unless all methods are asked for.
LibraryPlugin commandsflask <plugin command>src/flask/cli.py:600_load_plugin_commandsOnce per command group, loads every command installed packages register under the flask.commands entry-point group and adds each under its entry-point name.
LibraryWSGI callableenviron, start_response from the WSGI serversrc/flask/app.py:1679__call__ on FlaskLets the WSGI server call the application object directly, passing the request straight on to the WSGI app method so middleware can wrap that method instead.
LibraryDevelopment serverapp.run() in application codesrc/flask/app.py:641run on FlaskStarts Werkzeug's run_simple on 127.0.0.1:5000 by default, threaded, with reloader and debugger following debug mode. It returns at once without serving when FLASK_RUN_FROM_CLI is true, so it cannot start a second server under flask run.
LibraryHTTP routeGET /static/<path:filename> (app)src/flask/app.py:390 (rule added at app.py:356)send_static_file on FlaskServes a file from the application's static folder through send_from_directory, with the cache max age taken from the app's configuration. Raises RuntimeError if no static folder is set.
LibraryHTTP routeGET <blueprint static_url_path>/<path:filename>src/flask/blueprints.py:82 (rule added at sansio/blueprints.py:324)send_static_file on BlueprintThe same file-serving view for a blueprint's own static folder, registered when the blueprint is registered on an app with a static folder set.
LibraryTest harnessapp.test_client()src/flask/app.py:766test_clientReturns a client (FlaskClient unless the app names another class) that sends simulated requests through the full WSGI path without a server, keeping cookies between requests by default.
LibraryTest harnessapp.test_cli_runner()src/flask/app.py:824test_cli_runnerReturns a CLI runner (FlaskCliRunner by default) that invokes the app's Click commands in-process with the app already loaded.
TutorialHTTP routeGET /helloexamples/tutorial/flaskr/__init__.py:26helloReturns the plain text "Hello, World!", a smoke test that the application factory works.
TutorialHTTP routeGET, POST /auth/registerexamples/tutorial/flaskr/auth.py:46registerShows the sign-up form and, on POST, inserts a user with a Werkzeug password hash, reporting a taken username from the UNIQUE constraint and redirecting to login on success.
TutorialHTTP routeGET, POST /auth/loginexamples/tutorial/flaskr/auth.py:84loginShows the login form and, on POST, checks the username and password hash, then clears the session and stores the user id in it before redirecting to the index.
TutorialHTTP routeGET /auth/logoutexamples/tutorial/flaskr/auth.py:112logoutClears the session, which removes the stored user id, and redirects to the index.
TutorialHTTP routeGET / (endpoint index)examples/tutorial/flaskr/blog.py:16index (blog)Lists every post joined with its author's username, newest first, and renders the blog index page.
TutorialHTTP routeGET, POST /createexamples/tutorial/flaskr/blog.py:60createBehind the login_required decorator, shows the new-post form and, on POST, inserts a post owned by the logged-in user, requiring a title.
TutorialHTTP routeGET, POST /<int:id>/updateexamples/tutorial/flaskr/blog.py:86updateBehind login_required, loads the post (404 if missing, 403 if the user is not its author) and, on POST, updates its title and body.
TutorialHTTP routePOST /<int:id>/deleteexamples/tutorial/flaskr/blog.py:113deleteBehind login_required, checks the post exists and belongs to the user, deletes it and redirects to the index.
TutorialCLI commandflask init-dbexamples/tutorial/flaskr/db.py:41init_db_commandRuns schema.sql against the SQLite database, which drops and recreates the user and post tables, then prints a confirmation.
JavaScriptHTTP routeGET / (js defaults to fetch)examples/javascript/js_example/views.py:8index (javascript)Renders the fetch variant of the demo page, the default when no variant is named in the URL.
JavaScriptHTTP routeGET /<any(xhr, jquery, fetch):js>examples/javascript/js_example/views.py:9index (javascript)Renders the demo page for the named client technique, xhr, jquery or fetch, from the template of that name.
JavaScriptHTTP routePOST /addexamples/javascript/js_example/views.py:14add (javascript view)Reads two numbers from the form, defaulting each to 0, and returns their sum as JSON.
CeleryHTTP routeGET /examples/celery/src/task_app/__init__.py:19index (celery)Renders the page whose buttons start the example tasks and poll their results.
CeleryHTTP routeGET /tasks/result/<id>examples/celery/src/task_app/views.py:10resultLooks up a task by id in the Celery result backend and returns whether it is ready, whether it succeeded, and its value or current progress metadata.
CeleryHTTP routePOST /tasks/addexamples/celery/src/task_app/views.py:21add (celery view)Reads two integers from the form, queues the add task with them and returns the task id for polling.
CeleryHTTP routePOST /tasks/blockexamples/celery/src/task_app/views.py:29block (celery view)Queues the block task and returns its id at once, showing the web request does not wait for the work.
CeleryHTTP routePOST /tasks/processexamples/celery/src/task_app/views.py:35process (celery view)Queues the process task with the total read from the form and returns its id.
CeleryCelery taskmessage on the Redis brokerexamples/celery/src/task_app/tasks.py:7add (task)Runs in the Celery worker process and returns the sum of its two arguments, stored in the result backend.
CeleryCelery taskmessage on the Redis brokerexamples/celery/src/task_app/tasks.py:12block (task)Sleeps for 5 seconds in the worker and returns nothing; its result is not kept.
CeleryCelery taskmessage on the Redis brokerexamples/celery/src/task_app/tasks.py:17process (task)Counts up to the given total one second at a time, publishing a PROGRESS state with current and total after each step, then returns the final count.

Every Celery task runs inside a Flask application context: the example's application factory wraps the task class so each call pushes one before the task body runs, which is how a worker process outside any HTTP request can still read the app's configuration. The round trip from a web route through Redis to the worker and back is drawn in section 6.

4. Module boundaries

The module structure was measured with modules.cjs, which aggregates the call and import edges in the code graph by path prefix under src/. It found one module group, src/flask, holding all 24 Python files of the library, and no edge between two groups. It also set aside 137 edges that have one end outside src/; those are mostly the test suite calling into the library, which measures coverage rather than coupling.

The grouping rule, as modules.cjs printed it on its second line, verbatim:

Rule: grouped by path prefix under src/, starting at depth 2; a group over 25 files is split one level deeper, and only children with 8+ files are promoted.

The defaults were used (no --big or --min-child override). With 24 files, src/flask sits one file under the 25-file split threshold, so it is never split, and neither of its two sub-packages would be promoted anyway, since each holds 3 files against a promotion floor of 8.

Module groups

The first table from modules.cjs, in full, with one line on what the group owns. The classes and functions inside the group, with every call edge between them, are listed in the symbol index.

ModuleFilesWhat it owns
src/flask24The whole Flask framework: the Flask application class and the WSGI request pipeline, the combined application and request context, configuration, client-side sessions, blueprints, templating, JSON, signals, logging, the test client and the flask command line.

Cross-module edges

None: modules.cjs printed no cross-module call or import edge, so the second table has no rows to reproduce.

The tool's own explanation for an empty edge table is that the repository is infrastructure, config or image-build content. That is not the reason here. Flask is a Python library with real import structure; the table is empty because the entire library is a single package that falls below the split threshold, so every edge in it is internal to the one group. The generated module view is one box for the same reason, so it is not drawn (section 18).

Below the grouping: three sub-packages

The structure a reader needs sits one level below what the rule reports. Counting Python files with find src/flask -name '*.py' splits the 24 files into three sub-packages. This table is supplementary to the modules.cjs output, not part of it.

Sub-packageFilesWhat it owns
src/flask18Everything that touches I/O or the request globals: the WSGI application class Flask (app.py, 1,686 lines), the I/O-capable Blueprint (blueprints.py), the AppContext (ctx.py), the context-local proxies (globals.py), config.py, sessions.py, templating.py, helpers.py, signals.py, logging.py, wrappers.py, views.py, testing.py, debughelpers.py, typing.py, the package __init__.py, and the command line in cli.py (1,126 lines) with __main__.py.
src/flask/sansio3The parts that do no I/O: Scaffold (scaffold.py, 800 lines), the shared base holding route, hook and error-handler registration; App (app.py, 1,014 lines), the application core with configuration, URL map and blueprint registration; and the sans-I/O Blueprint with BlueprintSetupState (blueprints.py, 692 lines). Its README says the code exists so alternative implementations such as Quart can reuse it, and so it cannot do I/O or use the Flask globals.
src/flask/json3JSON handling: the module-level dump and load helpers and jsonify (__init__.py), the pluggable JSONProvider and DefaultJSONProvider (provider.py), and TaggedJSONSerializer (tag.py), which the cookie session uses to round-trip tuples, bytes, Markup, UUIDs and datetimes.

The one function this section names, so its import direction below can be read without opening the file:

FunctionWhereWhat it does
jsonifysrc/flask/json/__init__.py:138Builds a JSON response from its arguments using the active application's JSON provider, which is why the json sub-package imports current_app from the package above it.

The sansio layer is the base of a two-layer class design. Scaffold (sansio/scaffold.py:52) is subclassed by App (sansio/app.py:60), which Flask (app.py:108) subclasses to add WSGI, file serving and request handling; the same Scaffold is subclassed by the sans-I/O Blueprint (sansio/blueprints.py:119), which the Blueprint in blueprints.py:18 subclasses in turn.

Import directions between the sub-packages

One row per direction that has at least one import, read from the import statements. "Runtime" means the import executes when the module loads; "type only" means it sits under if t.TYPE_CHECKING: and exists only for the type checker.

FromToKindWhere
src/flasksrc/flask/sansioRuntimeapp.py:43 imports App; blueprints.py:10-12 imports the sans-I/O Blueprint, BlueprintSetupState and _sentinel; debughelpers.py:10 imports App. Type only in config.py:14, logging.py:12, templating.py:17-18.
src/flask/sansiosrc/flaskRuntimesansio/app.py:21-31 imports from ..typing, ..config, ..ctx, ..helpers, ..logging and ..templating; sansio/scaffold.py:17-19 from ..typing, ..helpers and ..templating; sansio/blueprints.py:8 from ..typing.
src/flasksrc/flask/jsonRuntime__init__.py:1 and :23 import the json package and jsonify; wrappers.py:10 imports json; sessions.py:14 imports TaggedJSONSerializer from json/tag.py.
src/flask/jsonsrc/flaskRuntimejson/__init__.py:6 imports current_app from ..globals. Type only in json/__init__.py:10 (..wrappers).
src/flask/sansiosrc/flask/jsonRuntimesansio/app.py:27-28 imports DefaultJSONProvider and JSONProvider from ..json.provider.
src/flask/jsonsrc/flask/sansioType onlyjson/provider.py:16 imports App under TYPE_CHECKING.

Two-way pairs

At the module level there is no two-way pair, because there is only one module. One level down there are two runtime two-way pairs, and both are cycles a layered picture of the package would hide:

A third pair, src/flask/sansio and src/flask/json, is two-way only for the type checker: the runtime direction is sansio to json, and the return direction is a TYPE_CHECKING import.

src/flask/app.py itself has no import from .json; it reaches JSON through the self.json provider attribute it inherits from App. The importers of src/flask/json inside src/flask are __init__.py:1, __init__.py:23, wrappers.py:10 and sessions.py:14.

5. Layered call graph

The backbone of Flask at run time is the request pipeline: the path every HTTP request takes from the WSGI server into the application and back out as a response. The figure draws it in five layers, from the WSGI entry at the top, through dispatch, view and error handling, and response building, to the context and session layer at the bottom. Every solid arrow is an edge present in docs/.analysis-cache/graphdata.json; all 22 were checked against the graph before drawing.

In the order the code runs, the path is __call__ -> wsgi_app -> request_context (from_environ) -> push -> full_dispatch_request -> preprocess_request / dispatch_request -> finalize_request -> make_response -> process_response, with handle_user_exception and handle_exception on the error path and pop running teardown in a finally block (src/flask/app.py:1653-1677).

Four links are drawn dashed because the graph cannot resolve them: wsgi_app calls push and pop on a local variable, ctx, and the session methods are reached through the self.session_interface attribute (_get_session calls open_session at src/flask/ctx.py:388; process_response calls save_session at src/flask/app.py:1467). They are calls the source makes, read from the source, not graph edges. Two graph edges are left out for legibility: preprocess_request and process_response also call ensure_sync, because every before-request and after-request hook is passed through it, just as the view is.

1 · WSGI entry 2 · Dispatch 3 · View and error handling 4 · Response 5 · Context and session ctx.push() and ctx.pop(error) through a local variable, not a graph edge Flask.__call__ wsgi_app full_dispatch_request preprocess_request dispatch_request raise_routing_exception async_to_sync ensure_sync make_default_options_response handle_user_exception handle_http_exception log_exception handle_exception finalize_request make_response process_response request_context AppContext.from_environ AppContext.push AppContext.pop AppContext._get_session AppContext.match_request sessions.py SecureCookieSessionInterface open_session get_signing_serializer save_session request path (graph edge) error path (graph edge) other graph edge call through a variable or attribute, not in the graph
Figure 5.1 · request pipeline call graphDrawn from the code graph rather than from reading the code: 22 solid edges, each present in graphdata.json, and 4 dashed links the graph cannot follow because they go through the local ctx or self.session_interface. Accented boxes are the path every successful request takes; red boxes are the error path. Flask methods live in src/flask/app.py, AppContext methods in src/flask/ctx.py, and the session methods in src/flask/sessions.py.

What the layers show that a single file does not. The request path and the error path are separate chains that meet again at finalize_request: a view's own exception goes to handle_user_exception inside full_dispatch_request and still finishes there, while an exception nothing handles escapes to wsgi_app, which hands it to handle_exception, and that reaches finalize_request again with its safe mode on. Every view, hook and error handler is called through ensure_sync, which is the single point where an async def function is bridged into the synchronous worker by async_to_sync. The context layer at the bottom is set up before dispatch (push opens the session and matches the URL) and torn down after the response by pop, in the finally block of wsgi_app. The session layer touches the request only twice: open_session on the way in and save_session on the way out, both through get_signing_serializer.

The session is not loaded lazily for a request, whatever the 3.2 note in the AppContext docstring says ("loaded the first time it is accessed", src/flask/ctx.py:295-297): push calls _get_session unconditionally whenever the context carries a request (src/flask/ctx.py:436-439, commented "Open the session at the moment that the request context is available"), so the cookie is read and verified on every push. A context without a request has no session at all.

Functions drawn

One row for every function in the figure, in layer order, with the file and line of its definition.

Functions in the request pipeline call graph 25 rows
FunctionLayerWhereWhat it does
__call__WSGI entrysrc/flask/app.py:1679The method the WSGI server calls on the Flask object for each request. It only forwards to wsgi_app, so middleware can wrap that attribute without losing the application object.
wsgi_appWSGI entrysrc/flask/app.py:1627The real WSGI application: builds the context for the request, pushes it, runs the full dispatch, and passes any unhandled exception to handle_exception. Its finally block always pops the context with the error, which runs teardown.
full_dispatch_requestDispatchsrc/flask/app.py:1023Marks the first request as seen, sends the request-started signal, runs the before-request hooks and then the view, routing any exception to handle_user_exception. Whatever comes back is turned into a response by finalize_request.
preprocess_requestDispatchsrc/flask/app.py:1409Runs the URL value preprocessors and then the before-request functions registered on the app and on each blueprint handling the request. If one returns a value, that value is used as the response and the view is skipped.
dispatch_requestDispatchsrc/flask/app.py:993Re-raises any routing error found during URL matching, answers an automatic OPTIONS request itself, and otherwise calls the view function registered for the matched endpoint with the URL arguments.
raise_routing_exceptionDispatchsrc/flask/app.py:566Raises the routing exception stored on the request. In debug mode a redirect that would drop a form body is replaced with an explanatory error instead.
ensure_syncView and error handlingsrc/flask/app.py:1108Returns a plain function unchanged and wraps an async def function with async_to_sync. Views, hooks, error handlers and signal receivers all pass through it.
async_to_syncView and error handlingsrc/flask/app.py:1122Wraps a coroutine function with asgiref's async_to_sync so a synchronous WSGI worker can call it and wait for the result. Raises RuntimeError if Flask was installed without the async extra.
make_default_options_responseView and error handlingsrc/flask/app.py:1092Builds the automatic response to an OPTIONS request: an empty response whose Allow header lists the methods the URL accepts.
handle_user_exceptionView and error handlingsrc/flask/app.py:880Handles an exception raised during dispatch: HTTP exceptions go to handle_http_exception, others to a registered error handler for their type. With no handler it re-raises, which sends the error up to wsgi_app.
handle_http_exceptionView and error handlingsrc/flask/app.py:841Looks up a registered error handler for an HTTP exception by code and class and calls it. Proxy exceptions with no code, routing redirects and unhandled codes are returned as the response unchanged.
handle_exceptionView and error handlingsrc/flask/app.py:916Handles an exception nothing else caught: sends the got-request-exception signal, then re-raises if exceptions propagate (debug or testing by default), otherwise logs it and returns a 500 through any registered 500 handler. The result goes through finalize_request in safe mode.
log_exceptionView and error handlingsrc/flask/app.py:973Writes the exception and traceback to the application logger at error level, with the request path and method in the message.
finalize_requestResponsesrc/flask/app.py:1056Turns a view's return value into a response, runs after-request processing and sends the request-finished signal. In the safe mode used after an error, a failure in that processing is logged instead of raised.
make_responseResponsesrc/flask/app.py:1267Converts whatever a view returned (string, bytes, dict or list as JSON, generator, tuple with status and headers, or a WSGI callable) into the application's response class, rejecting None.
process_responseResponsesrc/flask/app.py:1441Runs the per-request after-request callbacks and then the blueprint and app after-request functions in reverse registration order. It then saves the session onto the response unless the session is the null session.
request_contextContext and sessionsrc/flask/app.py:1562Creates the AppContext for one request from the WSGI environment by calling from_environ.
from_environContext and sessionsrc/flask/ctx.py:340Builds the application's request object from the WSGI environment, gives it the app's JSON provider, and returns a new context holding the app and that request.
pushContext and sessionsrc/flask/ctx.py:416Makes the context the active one in a context variable and sends the appcontext-pushed signal, counting nested pushes. For a request it then opens the session and matches the URL.
popContext and sessionsrc/flask/ctx.py:446Deactivates the context, raising if it is not the active one, and on the final pop runs request and app teardown, closes the request and sends appcontext-popped. Errors from those steps are collected and raised together at the end.
_get_sessionContext and sessionsrc/flask/ctx.py:381Opens the session through the application's session interface if it is not already open (push calls it for every request) and caches it on the context. Falls back to a null session when the interface returns none, as it does with no secret key.
match_requestContext and sessionsrc/flask/ctx.py:405Matches the request URL against the URL map and stores the matched rule and view arguments on the request, or stores the routing exception for dispatch to raise later.
open_sessionContext and sessionsrc/flask/sessions.py:323Reads the session cookie and verifies its signature and age, returning the session data, or an empty session if the cookie is missing, tampered with or expired. Returns nothing when there is no secret key.
save_sessionContext and sessionsrc/flask/sessions.py:337Writes the signed session cookie onto the response with the configured cookie flags, deletes it when the session was emptied, and adds Vary: Cookie when the session was accessed.
get_signing_serializerContext and sessionsrc/flask/sessions.py:303Builds the itsdangerous timed serializer that signs session cookies, with the current secret key plus any fallback keys so old cookies still verify during rotation. Returns nothing when no secret key is set.

6. Boundary-crossing flows

Flask runs inside one process: whatever WSGI server the application developer chooses calls the Flask object once per request, and the framework itself makes no outbound calls. So the flows worth drawing as sequences are the few where work or state leaves that call. There are five. A request arrives over the network into a server worker. Session state goes out to the browser in a signed cookie and comes back on the next request. An async view hands control to an event loop inside the worker. flask run splits into a watching parent and a serving child process. In the celery example, a task leaves the web process through Redis and is run by a separate worker process. Dispatch, error handling and response building inside one request are ordinary control flow and are covered by the call graph in section 5, not drawn again here.

FlowBoundary crossedFunctions involvedWhat it does
WSGI requestNetwork and process: browser to the server worker, then the WSGI callable interface into Flask__call__, wsgi_app, request_context, from_environ, push, full_dispatch_request, finalize_request, popTurns one HTTP request into one response inside one worker, with a context pushed for its duration and popped in a finally block.
Session cookie round tripClient: session state is held by the browser between requests_get_session, open_session, get_signing_serializer, make_null_session, process_response, save_sessionVerifies the signed cookie on the way in and signs the updated session on the way out; the server keeps no session store.
Async viewAsync: a coroutine run on an event loop driven by asgiref, inside the sync workerdispatch_request, ensure_sync, async_to_syncLets an async def view run under WSGI by blocking the worker thread until the coroutine finishes.
Development server reloaderProcess: the flask CLI process spawns and replaces a child server processmake_context, run_command, load_app, run_simple, runServes the app from a child process that is restarted on code changes, and keeps an unguarded app.run() from starting a second server.
Celery task round tripProcess: web process to Redis to a Celery worker process, and back by pollingadd, block, process, result, celery_init_appMoves slow work out of the request: the web process enqueues and returns an id, the worker runs the task in an app context, the browser polls for the result.

WSGI request

The boundary is the network hop from the browser to the server and the WSGI calling convention between the server and Flask. The server owns sockets, threads or processes; Flask owns everything from __call__ onwards. wsgi_app builds an AppContext from the environ, pushes it, dispatches, and returns the response iterable to the server. The context is popped in a finally block before the server iterates the body, so teardown always runs, and a streamed body that needs the request must hold the context itself (stream_with_context). The source is src/flask/app.py:1627-1686 and src/flask/ctx.py:416-504.

network and process boundary Browserclient WSGI server workergunicorn, Werkzeug ... Flask appFlask.wsgi_app AppContextctx.py View functionregistered route HTTP request app(environ, start_response) via __call__ request_context(environ): from_environ builds the Request push(): set contextvar, open session, match URL full_dispatch_request: preprocess_request, then dispatch_request return value (str, dict, tuple, Response ...) finalize_request: make_response, process_response, save_session response(environ, start_response): body iterable pop(error) in finally: teardown functions, signals HTTP response, body iterated after the pop
Figure 6.1 · WSGI requestOne request inside one server worker. The only process boundary is the HTTP hop on the left; everything to its right runs in the worker that called the Flask object, and the context is popped before the server writes the body.

Session cookie round trip

The boundary is the client: the default SecureCookieSessionInterface stores the whole session in a signed cookie, whose signing, age limit and key rotation are set out in section 8. On the way in, a bad signature or an expired timestamp gives an empty session rather than an error. With no SECRET_KEY, open_session returns nothing and make_null_session supplies a NullSession, which reads as empty and raises RuntimeError on any write. On the way out, save_session deletes the cookie if the session was emptied, sets it again only when it was modified or when a permanent session is refreshed on each request, and adds Vary: Cookie whenever the session was accessed. The source is src/flask/sessions.py:303-385.

The way in is not lazy, despite the 3.2 note in the AppContext docstring that the session "is loaded the first time it is accessed" (section 5). The code in src/flask/ctx.py:436-444 opens it during push for every request context ("Open the session at the moment that the request context is available"), before URL matching, so custom URL converters can read it. A context without a request has no session at all. What is deferred is only the accessed flag, which is set when the view reads the session proxy, not when push opens it.

trust boundary: the client holds the state Browserholds the cookie AppContextctx.py SecureCookieSessionInterfacesessions.py itsdangerousURLSafeTimedSerializer Cookie: session=payload.timestamp.signature push: _get_session, then open_session get_signing_serializer: fallbacks + SECRET_KEY loads(cookie, max_age): bad or expired = empty SecureCookieSession, or NullSession without a key the view reads and writes session; writes mark it modified process_response: save_session (not for NullSession) dumps(dict(session)) signed with the current key Set-Cookie: session=...; HttpOnly; Vary: Cookie
Figure 6.2 · session cookie round tripThe session lives in the browser between requests. The server keeps nothing: it verifies the signature on the way in and signs again on the way out, so the boundary crossed is the client, not a store.

Async view

The boundary is between synchronous WSGI and a coroutine. dispatch_request passes every view through ensure_sync, which returns plain functions unchanged and wraps async def functions with async_to_sync. That method imports asgiref's async_to_sync and raises RuntimeError asking for the async extra when asgiref is missing. The worker thread then blocks until the coroutine completes, so the request still occupies one worker for its whole length. Before-request, after-request and teardown functions, error handlers and signal receivers go through the same wrapper. The source is src/flask/app.py:1108-1143.

async boundary: event loop driven by asgiref WSGI worker threadsynchronous Flaskdispatch_request ensure_syncasync_to_sync asgiref event loopasync_to_sync Coroutine viewasync def full_dispatch_request, then dispatch_request ensure_sync(view function) coroutine function? wrap with async_to_sync sync wrapper (RuntimeError without asgiref) wrapper(**view_args): the worker thread blocks here run the coroutine await I/O result return value; the worker thread resumes
Figure 6.3 · async viewThe coroutine runs on an event loop that asgiref drives while the WSGI worker thread waits. The request still occupies one worker from start to finish; the async boundary sits inside that worker.

Development server reloader

The boundary is between two operating system processes. FlaskGroup.make_context sets FLASK_RUN_FROM_CLI=true in the environment before any command runs (src/flask/cli.py:667), and Flask.run returns immediately when it sees that value (src/flask/app.py:704-716), printing a warning outside the reloader. run_command loads the application and calls Werkzeug's run_simple with the reloader and debugger on when debug mode is on (src/flask/cli.py:953-992). With the reloader on, the process the developer started only watches files and runs the server in a child process with the same arguments and environment, replacing it when a watched file changes. If loading the app fails inside the reloaded child, run_command prints the traceback and serves a stub application that raises the same error on every request, so the server stays up and the debugger can show it. The reloader itself is Werkzeug code, outside this repository.

process boundary Developer shell flask CLI processFlaskGroup, reloader parent Child server processsame argv and environment Application modulethe --app target flask --app hello --debug run make_context: FLASK_RUN_FROM_CLI=true run_command: load_app imports the app; a stray app.run() returns at once run_simple(use_reloader=True) spawns the child load_app again; app.run() still a no-op serve 127.0.0.1:5000, threaded, debugger on a watched file changes: the child exits spawn a fresh child with the new code
Figure 6.4 · development server reloaderThe reloader is Werkzeug's: the process the developer started only watches, and the server runs in a child it replaces. FLASK_RUN_FROM_CLI is what stops an unguarded app.run() in the imported module from starting a second, blocking server in either process.

Celery task round trip

The boundary is two process hops through Redis. The example in examples/celery points Celery at redis://localhost as both broker and result backend (examples/celery/src/task_app/__init__.py:11-12), and celery_init_app gives every task a base class whose call pushes app.app_context(), so a task can use the application's configuration and extensions in the worker process. The add, block and process routes enqueue the matching task with delay and return its id at once; the result route polls with AsyncResult. add and process keep their results; block uses the default task_ignore_result=True, so it stores none, and process reports progress through a custom PROGRESS state. Retries and failure policy belong to Celery and are not configured in the example.

process boundary process boundary Browserexample page Flask web processtask_app views Redisbroker and result backend Celery worker processFlaskTask POST /tasks/add with a and b add.delay(a, b): message to the broker {"result_id": ...} the worker takes the task app_context() pushed, add runs result written to the backend GET /tasks/result/<id>, polled AsyncResult(id): ready(), get() {"ready", "successful", "value"}
Figure 6.5 · celery task round tripThe only flow in the repository that leaves the web process for another process. Redis sits between the two; the web process never waits for the task, and the browser learns the outcome by polling.

Functions in these flows

Functions named in this section 32 rows
FunctionWhereWhat it does
__call__src/flask/app.py:1679The WSGI entry point the server calls. It only forwards to wsgi_app, so middleware can wrap that attribute without losing the app object.
wsgi_appsrc/flask/app.py:1627Creates and pushes the request's context, dispatches it, turns an unhandled exception into a response, and pops the context in a finally block.
request_contextsrc/flask/app.py:1562Builds an AppContext carrying request data for a WSGI environ by calling from_environ.
from_environsrc/flask/ctx.py:340Creates the Request object from the environ, attaches the app's JSON provider to it, and returns a new context holding it.
pushsrc/flask/ctx.py:416Makes the context active in a contextvar, sends appcontext_pushed, opens the session and matches the URL. A nested push only increments a counter.
popsrc/flask/ctx.py:446Decrements the push count and, on the last pop, runs teardown functions, closes the request, resets the contextvar and raises any errors collected on the way.
stream_with_contextsrc/flask/helpers.py:63Wraps a response generator so the current context stays pushed while the server iterates it, letting a streamed body use the request proxy after wsgi_app has returned.
app_contextsrc/flask/app.py:1542Creates an AppContext with no request data, used for CLI commands, setup code and, in the celery example, each task.
full_dispatch_requestsrc/flask/app.py:1023Marks the first request, sends request_started, runs before-request functions and the view, routes exceptions to the user handlers, then finalizes the response.
preprocess_requestsrc/flask/app.py:1409Runs URL value preprocessors and before-request functions for the app and the matched blueprints; a non-None return value short-circuits the view.
dispatch_requestsrc/flask/app.py:993Raises the routing exception if matching failed, answers automatic OPTIONS requests, and otherwise calls the matched view through ensure_sync.
finalize_requestsrc/flask/app.py:1056Converts a view's return value into a response and runs response processing; in error-handler mode it logs a failure there instead of raising it.
make_responsesrc/flask/app.py:1267Turns any allowed view return value (string, bytes, dict, list, tuple, iterator, Response or WSGI callable) into a Response object.
process_responsesrc/flask/app.py:1441Runs after-request functions in reverse registration order, then saves the session unless it is a null session.
_get_sessionsrc/flask/ctx.py:381Opens the session through the app's session interface if it is not already open (push calls it for every request), falling back to a null session when none can be opened.
open_sessionsrc/flask/sessions.py:323Reads the session cookie and verifies its signature and age; returns an empty session on a bad or expired cookie and None when no secret key is set.
get_signing_serializersrc/flask/sessions.py:303Builds the itsdangerous serializer from SECRET_KEY and any SECRET_KEY_FALLBACKS, or returns None when there is no secret key.
make_null_sessionsrc/flask/sessions.py:150Returns a NullSession, an empty session that raises a clear error on any write because no secret key is set.
save_sessionsrc/flask/sessions.py:337Deletes, skips or re-signs and sets the session cookie with the configured name, domain, path, Secure, HttpOnly, SameSite and expiry, and adds Vary: Cookie.
ensure_syncsrc/flask/app.py:1108Returns a plain function unchanged and wraps a coroutine function so a synchronous WSGI worker can call it.
async_to_syncsrc/flask/app.py:1122Wraps a coroutine function with asgiref's async_to_sync, raising a RuntimeError that asks for the async extra when asgiref is not installed.
make_contextsrc/flask/cli.py:657Sets FLASK_RUN_FROM_CLI so app.run() becomes a no-op, and attaches the ScriptInfo that commands use to load the app.
run_commandsrc/flask/cli.py:934The flask run command: loads the app and starts Werkzeug's development server with the host, port, reloader, debugger, threading and TLS options given.
load_appsrc/flask/cli.py:333Finds and imports the application from --app, FLASK_APP, a factory, or wsgi.py or app.py in the current directory.
run_simplewerkzeug.servingWerkzeug's development server, outside this repository; it serves a WSGI app and can run it under the reloader and the interactive debugger.
runsrc/flask/app.py:641Flask.run: starts the development server from code, defaulting to 127.0.0.1:5000, threaded; it does nothing when called under flask run.
celery_init_appexamples/celery/src/task_app/__init__.py:29Creates the Celery app from the Flask config's CELERY mapping with a task class that runs every task inside an app context, and stores it in app.extensions.
addexamples/celery/src/task_app/views.py:22Route that reads a and b from the form, enqueues the add task (which returns their sum, examples/celery/src/task_app/tasks.py:8), and returns the task id.
blockexamples/celery/src/task_app/views.py:30Route that enqueues the block task, which sleeps for five seconds and keeps no result, and returns the task id.
processexamples/celery/src/task_app/views.py:36Route that enqueues the process task, which reports a PROGRESS state once a second for total steps, and returns the task id.
resultexamples/celery/src/task_app/views.py:11Route that looks up a task id with AsyncResult and returns whether it is ready, whether it succeeded, and its value or progress.
delaycelery (library)Celery's shortcut for sending a task message to the broker with the given arguments; it returns an AsyncResult without waiting.

7. State machines

Two genuine state machines live in the framework, each with states that can be named from a field in the source and transitions that refuse to happen out of order. The first is the AppContext lifecycle: every request and every CLI command gets one AppContext, which is created, pushed (possibly several times), and torn down once, and which raises RuntimeError when popped out of turn (src/flask/ctx.py:416-504). The second is the application setup lock: an application accepts setup calls such as route registration until it handles its first request, and from then on every setup method raises (src/flask/sansio/app.py:405-420, src/flask/sansio/scaffold.py:42-50, src/flask/app.py:1045). The task states in the celery example (PENDING, PROGRESS, SUCCESS and the rest) are Celery's own machine, held in Redis by Celery; the example only reads them, so they are not drawn here.

AppContext lifecycle

The state is held in two fields. _cv_token is set while the context is the active value of the module's contextvar, and _push_count counts nested pushes. A first push sets the contextvar, sends appcontext_pushed and, for a request, opens the session and matches the URL. A second push of the same context, which streaming and the test client do, only increments the counter, and every pop but the last only decrements it. The final pop runs the request teardown functions, closes the request, runs the app-context teardown functions, resets the contextvar and sends appcontext_popped, collecting any exception raised along the way and raising them together at the end. pop refuses with RuntimeError when the context was never pushed, when no context is active, or when a different context is active, so contexts must be popped in the reverse order they were pushed. After teardown the fields are back to their initial values and the same object can be pushed again; the interactive debugger and the test client both do this to keep the request proxy readable after a request, and the class docstring warns that teardown will then run a second time.

Created_push_count = 0 Pushed (active)_cv_token set, count >= 1 Torn downcontextvar reset RuntimeErrornot pushed / not active push(): contextvar,signal, session, URL nested push(), or pop() with count > 1:only the counter moves final pop(exc): teardown,request.close, signal push() again (debugger, test client) pop() whileanother is active pop() before push()
Figure 7.1 · AppContext lifecycleOne object per request or CLI command. Nested pushes only move the counter; teardown runs once, on the pop that brings it back to zero. A torn-down context can be pushed again, which is why teardown can run twice.

Application setup lock

The state is one boolean, _got_first_request, false when the application is built and set true by full_dispatch_request at the start of every request. Every registration method on Scaffold, App and Blueprint is wrapped by the setupmethod decorator, which calls _check_setup_finished before the method runs; on an application that check raises AssertionError once the flag is true, with a message saying changes would not be applied consistently. The one transition back is in Flask.run: when the development server returns, its finally block resets the flag, so an application restarted from an interactive shell can be set up again (src/flask/app.py:759-764). A Blueprint has the same lock on its own flag, _got_registered_once, set the first time the blueprint is registered on an application (src/flask/sansio/blueprints.py:213-221, src/flask/sansio/blueprints.py:320). The base Scaffold version of _check_setup_finished raises NotImplementedError, so each subclass must define its own.

Setup_got_first_request = False Serving_got_first_request = True AssertionErrorsetup method refused @setupmethod calls: route,before_request, errorhandler ... first full_dispatch_request Flask.run finally: server stopped any @setupmethod call:_check_setup_finished raises
Figure 7.2 · application setup lockThe application is mutable until it has handled one request and frozen after. A Blueprint carries the same lock on _got_registered_once, set the first time it is registered on an application.

Transitions

MachineFromToTriggerWhat it does
AppContext lifecycle(none)Createdfrom_environ (src/flask/ctx.py:340), or app_context (src/flask/app.py:1542) for a context with no requestBuilds a new context with a push count of zero; from_environ first creates the Request from the WSGI environ, app_context creates one without request data.
AppContext lifecycleCreatedPushedpush (src/flask/ctx.py:416)Makes the context the active value of the contextvar and sends appcontext_pushed; for a request it also opens the session and matches the URL.
AppContext lifecyclePushedPushedpush again, or pop while the count is above oneA nested push only increments _push_count and a non-final pop only decrements it; no signal, teardown or matching runs.
AppContext lifecyclePushedTorn downfinal pop (src/flask/ctx.py:446)Runs request and app-context teardown functions, closes the request, resets the contextvar and sends appcontext_popped, then raises any errors it collected.
AppContext lifecycleCreated, or Pushed but not activeRuntimeErrorpop out of turnRefuses to pop a context that was never pushed, when no context is active, or when another context is the active one.
AppContext lifecycleTorn downPushedpush again, by the debugger or test clientPushes the same object a second time so the request proxy stays readable after the response; teardown runs again on the next final pop.
Application setup lockSetupServingfull_dispatch_request (src/flask/app.py:1023)Sets _got_first_request to true at the start of every request, then runs before-request functions, the view and the error handlers and finalizes the response.
Application setup lockServingAssertionErrorsetupmethod (src/flask/sansio/scaffold.py:42) calling _check_setup_finished (src/flask/sansio/app.py:411)The decorator runs the check before every registration method; the check raises AssertionError naming the method once the application has handled a request.
Application setup lockServingSetuprun (src/flask/app.py:641) returningFlask.run starts Werkzeug's development server; when it returns, its finally block sets _got_first_request back to false.
Blueprint setup lockOpenRegisteredfirst registration on an application (src/flask/sansio/blueprints.py:320), then _check_setup_finished (src/flask/sansio/blueprints.py:213)Registration sets _got_registered_once; after that the blueprint's check raises AssertionError for any further setup call.

8. Security model

Flask is a library, so its security model is the boundaries it draws around a request and the defaults it ships. Authentication and authorisation are deliberately left to the application. What the framework itself does is sign the session cookie, escape templates, check paths for static files, enforce form size limits, optionally check the Host header, and keep its interactive debugger off unless asked. The repository's own attack surface is its release pipeline, which is locked down in CI.

Trust boundaries

BoundaryWhat crosses itWhat the framework does there
Browser to WSGI server to applicationUntrusted HTTP: path, headers, query string, form and bodyWerkzeug parses the request. Flask checks the Host header against TRUSTED_HOSTS when it is set, and form parsing stops at 500,000 bytes held in memory and 1,000 parts. Body size has no limit unless MAX_CONTENT_LENGTH or the server sets one.
The session cookie held by the clientAll session state, round-tripped on every requestSigned with HMAC, so tampering or expiry is detected and the session comes back empty. It is not encrypted, so the user can read everything in it (figure 6.2).
Template data to HTMLValues a view passes into a templateJinja autoescaping is on for .html, .htm, .xml, .xhtml and .svg templates and for templates rendered from a string, so values are escaped unless marked safe.
Client path to the file systemA filename taken from the URLStatic files and send_from_directory join the path with Werkzeug's safe join, which refuses paths that would leave the directory and answers 404.
The debuggerTracebacks and, with code execution on, a Python console in the browserWerkzeug's interactive debugger is on only in debug mode (--debug or FLASK_DEBUG). The development server binds 127.0.0.1 by default, and the flask run docstring says it is for development only.
Maintainer to PyPIThe released packageA tag starts publish.yaml. It builds once, creates a draft GitHub release, and uploads to PyPI through trusted publishing from the protected publish environment, the only job granted id-token: write.

Security-relevant defaults

Flask.default_config has 29 keys (src/flask/app.py:205-235). These eight decide the security posture an application starts with. Each can be changed per application; section 9 covers how configuration is loaded.

KeyDefaultWhat it governsAt the default
SECRET_KEYNoneThe key that signs session cookies (and that extensions use for their own signing)No session can be saved. A NullSession is used, and it raises RuntimeError on the first write, not at startup.
SECRET_KEY_FALLBACKSNoneOlder keys still accepted when verifying, for rotationOnly the current key verifies, so changing SECRET_KEY invalidates every existing session.
SESSION_COOKIE_HTTPONLYTrueWhether page scripts can read the session cookieScripts cannot read it.
SESSION_COOKIE_SECUREFalseWhether the browser sends the cookie only over HTTPSThe cookie is also sent over plain HTTP.
SESSION_COOKIE_SAMESITENoneThe cookie's SameSite attributeNo attribute is set, so the browser applies its own default.
TRUSTED_HOSTSNoneThe Host header values the app acceptsAny Host header is accepted and used to build URLs.
PERMANENT_SESSION_LIFETIME31 daysThe age limit applied to every session signature, and the expiry of a permanent session's cookieA signed cookie verifies for up to 31 days after it was last issued.
MAX_CONTENT_LENGTHNoneThe largest request body the app will readNo limit, unless the WSGI server sets one.

Sessions and key rotation

Sessions are stored client-side in a signed (not encrypted) cookie named "session". The signer is itsdangerous's URLSafeTimedSerializer with salt cookie-session, HMAC key derivation and SHA-1. max_age comes from PERMANENT_SESSION_LIFETIME, and SECRET_KEY_FALLBACKS is accepted for key rotation: verifying tries the fallbacks as well as the current key, while new cookies are always signed with the current key. A cookie that fails verification gives an empty session instead of an error. There is no server-side session record, so logging out clears the cookie only in the browser that logs out. A copied cookie stays valid until its signature ages past the lifetime or the key changes. A session that is not marked permanent gets a browser-session cookie with no expiry, but its signature is still limited to the same 31 days.

FunctionWhereWhat it does
get_signing_serializersrc/flask/sessions.py:303Builds the itsdangerous serializer from SECRET_KEY, with any SECRET_KEY_FALLBACKS ahead of it, or returns None when there is no secret key.
open_sessionsrc/flask/sessions.py:323Reads the session cookie and verifies its signature and age. A bad or expired cookie gives an empty session, and a missing secret key gives None.
save_sessionsrc/flask/sessions.py:337Deletes the cookie, leaves it alone, or re-signs and sets it with the configured Secure, HttpOnly, SameSite, domain, path and expiry, then adds Vary: Cookie.

Authentication

The framework has none, deliberately: it has no user model, login view or token type. The identity source is whatever the application provides. The tutorial shows the intended pattern. register stores a Werkzeug password hash in the "user" table. login checks the hash, clears the session and stores user_id in it. load_logged_in_user runs before every request and loads that user into g.user. logout clears the session. Token lifetime is therefore the session cookie's lifetime described above: up to 31 days of signature validity, with no server-side revocation short of changing the key.

Authorisation

The framework has none either. A route is public unless the application guards it. When a guard is forgotten, the view simply runs for anyone, and nothing in Flask notices. In the tutorial, login_required redirects anonymous users to the login page, and get_post returns 404 for a missing post and 403 when the logged-in user is not its author. Both checks are in the view layer of the example, not the framework.

Deliberately public, deliberately absent

Every registered route is reachable by anyone who can reach the server. When the application has a static folder, a /static/<path:filename> route is added that serves it through send_static_file, and blueprints with a static folder get one each. Three things are absent from core by design and left to the application or extensions. There is no CSRF protection: no token, no check, and the tutorial's forms carry none. There is no encryption of session data. There are no security response headers such as HSTS or a content security policy. A search of src/flask and examples for these finds nothing.

Supply chain and outbound calls

Every action in the five workflows is pinned to a commit SHA, every workflow starts from permissions: {}, checkout runs with persist-credentials: false, and zizmor audits the workflows. uv.lock is committed, and the pre-commit hooks run ruff, codespell and the uv lock check. The outbound-call evidence is clean. Six hosts are named outside tests (github.com, flask.palletsprojects.com, discord.gg, img.website.com, palletsprojects.com, pypi.org), all as project metadata, documentation links or docstring examples. The scan found no HTTP client, socket or download in the code, 0 install hooks and 0 lines matching a risk pattern. The one dynamic execution is in shell_command, which runs the file named by PYTHONSTARTUP through eval as the plain Python REPL does (src/flask/cli.py:1019-1022). That is the developer's own file on their own machine, so it is benign. Section 12 lists every host.

Functions named in this section

FunctionWhereWhat it does
make_null_sessionsrc/flask/sessions.py:150Returns a NullSession, an empty session that raises a clear error on any write because no secret key is set.
send_static_filesrc/flask/app.py:390, src/flask/blueprints.py:82The view behind the static route on an app or a blueprint. It serves a file from the static folder through send_from_directory with the configured cache age.
send_from_directorysrc/flask/helpers.py:543Sends a file from inside a directory, using Werkzeug's safe join so a client-supplied path cannot leave it; an unsafe or missing path is a 404.
shell_commandsrc/flask/cli.py:1000The flask shell command: starts an interactive Python shell in an app context, first running the PYTHONSTARTUP file if one is set.
registerexamples/tutorial/flaskr/auth.py:47Tutorial view that validates a username and password and inserts the user with a Werkzeug password hash, refusing a username that already exists.
loginexamples/tutorial/flaskr/auth.py:85Tutorial view that checks the password against the stored hash and, on success, clears the session and stores the user's id in it.
logoutexamples/tutorial/flaskr/auth.py:113Tutorial view that clears the session, including the stored user id, and redirects to the index.
load_logged_in_userexamples/tutorial/flaskr/auth.py:33Runs before every request; loads the user named by the session's user_id into g.user, or sets it to None.
login_requiredexamples/tutorial/flaskr/auth.py:19Tutorial view decorator that redirects to the login page when g.user is None and otherwise calls the view.
get_postexamples/tutorial/flaskr/blog.py:28Tutorial helper that loads a post with its author; it aborts with 404 if the post is missing and 403 if the current user is not the author.
evalPython built-inExecutes code compiled from a string. Here it runs the developer's PYTHONSTARTUP file in the shell's namespace.

Security rating

Security: 8/10, Good

Good: the outbound-call evidence is clean, sessions are HMAC-signed with an age limit and key rotation and fail loudly without a key, templates autoescape, static paths are safe-joined, and the release path is SHA-pinned, least-privilege and published through trusted publishing. It is not higher because the defaults leave the cookie's Secure flag off, SameSite unset, Host and body size unchecked, session contents readable by the client, and CSRF protection absent from core, all documented and left to the application. The technical assessment gives the reasoning per criterion.

9. Configuration and secrets

Flask has two configuration surfaces, and they are kept apart. The process environment steers the flask command line and the development server: which application to load, whether debug mode is on, where to bind. The application config (app.config, a Config dictionary created from Flask.default_config) steers what the application does once it is running: the secret key, cookie flags, size limits. The framework never copies the environment into app.config by itself; an application does that explicitly with one of the six loaders below, most simply from_prefixed_env, which turns FLASK_SECRET_KEY into SECRET_KEY.

There are 24 environment variables: 10 found by the evidence (FLASK_DEBUG, FLASK_RUN_FROM_CLI, FLASK_SKIP_DOTENV, PYTHONSTARTUP, YOURAPPLICATION_SETTINGS, and the test fixtures FOO, BAR, SPAM, EGGS, HAM) plus 14 read through click's auto_envvar_prefix FLASK, which FlaskGroup sets at src/flask/cli.py:585. Click names each one from the command and option, FLASK_OPTION on the group and FLASK_COMMAND_OPTION on a subcommand, as docs/cli.rst:154-157 documents. Only four are read by name in Flask's own code (FLASK_DEBUG, FLASK_SKIP_DOTENV, FLASK_RUN_FROM_CLI, PYTHONSTARTUP), and YOURAPPLICATION_SETTINGS appears only in a docstring; the 14 click variables exist because click reads one for every option. The five fixture variables are not configuration at all: they sit in tests/test_apps/.env and tests/test_apps/.flaskenv so that the dotenv tests have something to load.

One of the 14 is easy to miss. run_command carries its own --debug/--no-debug option (src/flask/cli.py:995 inserts _debug_option), so click also reads FLASK_RUN_DEBUG under the same FLASK_COMMAND_OPTION rule; its callback _set_debug then writes FLASK_DEBUG. The table below carries it as its own row.

Environment variables 24 rows
VariableDefaultRead atKindWhen it is absent
FLASK_APPnonesrc/flask/cli.py:453 (the -A/--app option), prefix from cli.py:585CLI, by clickload_app tries wsgi.py and then app.py in the current directory (cli.py:351); if neither holds an app it raises NoAppException, "Could not locate a Flask application" (cli.py:358-364). Built-in and plugin commands still list.
FLASK_DEBUGunset, meaning offsrc/flask/helpers.py:32 (get_debug_flag); src/flask/app.py:722 (Flask.run); written at cli.py:481CLI and app.run, by nameDebug mode is off: load_app sets app.debug to False, and the reloader and interactive debugger stay off. Any value other than 0, false or no turns it on.
FLASK_ENV_FILEnonesrc/flask/cli.py:517 (the -e/--env-file option)CLI, by clickOnly the default .flaskenv and .env files are loaded. A value that names a missing file is rejected by click's path check before anything loads.
FLASK_SKIP_DOTENVunset, meaning loadsrc/flask/helpers.py:43 (get_load_dotenv)CLI and app.run, by nameThe default dotenv files are loaded when python-dotenv is installed. Set to anything but 0, false or no, it skips them.
FLASK_RUN_FROM_CLIunsetset at src/flask/cli.py:667; read at src/flask/app.py:706internal flag, by nameFlask.run starts the development server as asked. When the flask command has set it to true, Flask.run prints a warning and returns, so a stray app.run() at import time cannot block a CLI command. Not meant to be set by hand.
FLASK_RUN_HOST127.0.0.1src/flask/cli.py:882CLI, by clickThe development server binds to the loopback interface only.
FLASK_RUN_PORT5000src/flask/cli.py:883CLI, by clickThe development server listens on port 5000.
FLASK_RUN_CERTnonesrc/flask/cli.py:884-889CLI, by clickThe server speaks plain HTTP. A value may be a certificate file, adhoc (needs the cryptography library) or the import path of an ssl.SSLContext.
FLASK_RUN_KEYnonesrc/flask/cli.py:890-896 (validated at cli.py:828-864)CLI, by clickFine with no certificate, or with an adhoc or SSLContext one. With a certificate file and no key the command stops with "Required when using --cert".
FLASK_RUN_RELOADnone, follows debugsrc/flask/cli.py:897-902, applied at cli.py:974CLI, by clickThe reloader is on exactly when debug mode is on.
FLASK_RUN_DEBUGGERnone, follows debugsrc/flask/cli.py:903-908, applied at cli.py:977CLI, by clickThe interactive debugger is on exactly when debug mode is on.
FLASK_RUN_WITH_THREADStruesrc/flask/cli.py:909-913CLI, by clickThe development server handles each request in its own thread.
FLASK_RUN_EXTRA_FILESnonesrc/flask/cli.py:914-922CLI, by clickThe reloader watches only the imported Python modules. Values are split on the OS path separator.
FLASK_RUN_EXCLUDE_PATTERNSnonesrc/flask/cli.py:923-932CLI, by clickNo file is excluded from triggering a reload.
FLASK_RUN_DEBUGnone, falls back to FLASK_DEBUGsrc/flask/cli.py:995 (the run command's --debug option), callback cli.py:468-482CLI, by clickDebug mode for flask run comes from FLASK_DEBUG or the group's --debug flag. When set, _set_debug rewrites FLASK_DEBUG to match.
FLASK_ROUTES_SORTendpointsrc/flask/cli.py:1048-1057CLI, by clickflask routes sorts its table by endpoint name. Click rejects a value outside endpoint, methods, domain, rule and match.
FLASK_ROUTES_ALL_METHODSfalsesrc/flask/cli.py:1058CLI, by clickflask routes hides the automatic HEAD and OPTIONS methods.
PYTHONSTARTUPunsetsrc/flask/cli.py:1019CLI, by nameflask shell starts with only the application's shell context. When it names a file, the shell runs that file first, as the plain Python REPL does (see section 12).
YOURAPPLICATION_SETTINGSnonesrc/flask/config.py:84, src/flask/config.py:107 (docstring)documentation exampleNothing: no code in the repository reads it. It illustrates from_envvar; an application that calls from_envvar("YOURAPPLICATION_SETTINGS") with the variable absent gets a RuntimeError (config.py:118), or False with silent=True.
FOOenv (from .env; .flaskenv says flaskenv)tests/test_apps/.env:1, tests/test_apps/.flaskenv:1; asserted at tests/test_cli.py:545test fixtureNo runtime effect. It proves .env wins over .flaskenv; if the files go, test_load_dotenv fails.
BARbar (from .flaskenv)tests/test_apps/.flaskenv:2; asserted at tests/test_cli.py:547test fixtureNo runtime effect. It proves a key set only in .flaskenv still loads.
SPAM1 (from .env)tests/test_apps/.env:2; asserted at tests/test_cli.py:549test fixtureNo runtime effect. It proves a key set only in .env loads.
EGGS2 in .env, 0 in .flaskenv; the test sets 3tests/test_apps/.env:3, tests/test_apps/.flaskenv:3; asserted at tests/test_cli.py:551test fixtureNo runtime effect. It proves a variable already in the environment is never overwritten by a dotenv file.
HAM火腿 (from .env)tests/test_apps/.env:4; asserted at tests/test_cli.py:553test fixtureNo runtime effect. It proves dotenv files are read as UTF-8.

Config loaders

Six methods on Config (src/flask/config.py) fill app.config. Every one keeps only upper-case keys, so a module's helpers and imports do not leak into the configuration. Which loaders run, and in what order, is the application's choice; the framework calls none of them itself. The tutorial calls from_mapping and then from_pyfile("config.py", silent=True); the celery example calls from_mapping and then from_prefixed_env.

LoaderWhereWhat it doesOn a missing or bad source
from_envvarsrc/flask/config.py:102Reads a file path from the named environment variable and loads that file with from_pyfile. It is a shortcut with a clearer error for the common "settings file named by an env var" pattern.Raises RuntimeError naming the variable when it is unset (config.py:118), or returns False with silent=True.
from_prefixed_envsrc/flask/config.py:126Copies every environment variable starting with FLASK_ (or a given prefix) into config with the prefix dropped, parsing each value as JSON. A double underscore in the name sets a key inside a nested dictionary.A value that does not parse is kept as a string without any message (config.py:160-165).
from_pyfilesrc/flask/config.py:187Executes a Python file relative to the config root path as a throwaway module, then loads its upper-case names through from_object.Re-raises the OSError with "Unable to load configuration file", or returns False with silent=True when the file is missing.
from_objectsrc/flask/config.py:218Loads the upper-case attributes of a module or class, importing it first when given a dotted string. The docstring recommends it for defaults, with the real values from a file.An import string that does not resolve raises Werkzeug's import error.
from_filesrc/flask/config.py:256Opens a data file and passes it to a caller-supplied loader such as json.load or tomllib.load, then hands the mapping to from_mapping.Re-raises the OSError with "Unable to load configuration file", or returns False with silent=True.
from_mappingsrc/flask/config.py:304Updates config from a mapping and keyword arguments, skipping keys that are not upper case. Always returns True.Not applicable: there is no external source to miss.

Defaults

Flask.default_config (src/flask/app.py:205-235) has 29 keys, so an application with no configuration at all still starts. They group into debug and error behaviour (DEBUG, TESTING, PROPAGATE_EXCEPTIONS, TRAP_BAD_REQUEST_ERRORS, TRAP_HTTP_EXCEPTIONS, EXPLAIN_TEMPLATE_LOADING), the secret and session cookie (SECRET_KEY, SECRET_KEY_FALLBACKS, PERMANENT_SESSION_LIFETIME, the seven SESSION_COOKIE_* keys and SESSION_REFRESH_EACH_REQUEST), URL building (SERVER_NAME, APPLICATION_ROOT, PREFERRED_URL_SCHEME, TRUSTED_HOSTS), size limits (MAX_CONTENT_LENGTH, MAX_FORM_MEMORY_SIZE, MAX_FORM_PARTS, MAX_COOKIE_SIZE) and file and template serving (USE_X_SENDFILE, SEND_FILE_MAX_AGE_DEFAULT, TEMPLATES_AUTO_RELOAD, PROVIDE_AUTOMATIC_OPTIONS). The security-relevant defaults are set out in section 8 and the size limits in section 15; neither is repeated here. A few keys are mirrored as attributes on the application (app.secret_key reads SECRET_KEY through a ConfigAttribute at src/flask/sansio/app.py:214), so the two always agree.

Dotenv files and precedence

When python-dotenv is installed (the dotenv extra), the flask command and Flask.run both call load_dotenv (src/flask/cli.py:698). It reads .flaskenv, then .env, then the --env-file path, each later file overriding the one before, and only then writes to the environment, skipping every key the real environment already has. So the order, lowest to highest, is .flaskenv, .env, --env-file, the real environment. The intended split, stated in docs/cli.rst, is that .flaskenv holds public CLI settings such as FLASK_APP and may be committed, and .env holds private values and should not be. Without python-dotenv the files are ignored with a yellow tip on stderr, and an explicit --env-file is refused by _env_file_callback.

How secrets are held and rotated

Flask has one secret of its own, SECRET_KEY, which signs the session cookie, and it lives in application config like any other key. The framework does not read it from any particular place; the application chooses a loader, and the documentation (docs/config.rst:560) shows FLASK_SECRET_KEY with from_prefixed_env. Rotation is built in: get_signing_serializer (src/flask/sessions.py:303) signs with the current key and also accepts any key in SECRET_KEY_FALLBACKS, so an operator can introduce a new key, keep the old one as a fallback until existing cookies expire, then drop it. Nothing expires a key on a schedule. A missing key is not caught at startup: requests still work, the session is a NullSession that can be read but raises RuntimeError on the first write (src/flask/sessions.py:83-97), so the gap shows when a view first stores something in the session or flashes a message.

The tutorial sets SECRET_KEY="dev" in its factory (examples/tutorial/flaskr/__init__.py:11) with a comment that it should be overridden, and loads instance/config.py over it when that file exists; the instance folder is not in the repository. The celery example sets no key and relies on from_prefixed_env. The tests use fixed keys (tests/conftest.py:32, tests/static/config.toml:2). There is no .env.example or .env.sample (both probed absent in section 10); the only committed dotenv files are the test fixtures above, and they hold no secrets. The reference for every config key is docs/config.rst.

The repository's own pipeline keeps no long-lived secret. The publish workflow uploads to PyPI through trusted publishing with a short-lived id-token: write grant in the protected publish environment, and creates the draft GitHub release with the per-run github.token (.github/workflows/publish.yaml:34-60). Every workflow starts from permissions: {}.

Other functions named in this section

FunctionWhereWhat it does
get_debug_flagsrc/flask/helpers.py:28Returns whether debug mode is on, from FLASK_DEBUG. Unset, 0, false and no mean off.
get_load_dotenvsrc/flask/helpers.py:36Returns whether the default dotenv files should be loaded, which is the caller's default unless FLASK_SKIP_DOTENV says otherwise.
load_dotenvsrc/flask/cli.py:698Merges .flaskenv, .env and an optional extra file and sets each key not already in the environment. Returns False and prints a tip when python-dotenv is missing.
_set_debugsrc/flask/cli.py:468Callback of the --debug/--no-debug option: when the flag or its environment variable was given, writes FLASK_DEBUG so an application factory can see it early.
_env_file_callbacksrc/flask/cli.py:493Callback of -e/--env-file: refuses the option when python-dotenv is missing, otherwise calls load_dotenv with the given file and the defaults.
make_contextsrc/flask/cli.py:657FlaskGroup's context factory: sets FLASK_RUN_FROM_CLI and creates the ScriptInfo that later loads the application.
load_appsrc/flask/cli.py:333Finds and imports the application from --app/FLASK_APP, a factory, or wsgi.py/app.py, and applies the debug flag. Raises NoAppException when nothing is found.
runsrc/flask/app.py:641Flask.run: loads dotenv files, resolves debug, host and port, and starts Werkzeug's development server. Returns at once when called under the flask command.
run_commandsrc/flask/cli.py:934The flask run command: loads the application and starts the development server with the host, port, TLS, reload and thread options above.
get_signing_serializersrc/flask/sessions.py:303Builds the itsdangerous serializer that signs session cookies with SECRET_KEY and accepts SECRET_KEY_FALLBACKS. Returns None when no key is set, which leads to a NullSession.

Configuration and secrets rating

Configuration and secrets: 7/10, Good

Good. Configuration is externalised through one Config object with six loaders, 29 documented defaults, dotenv files with a clear precedence order, and every CLI option readable from a FLASK_ variable; from_envvar fails fast with a clear message, and secrets rotate through SECRET_KEY_FALLBACKS. The gaps a reader can name: a missing SECRET_KEY shows only when a session is first written, not at startup; from_prefixed_env silently keeps a value as a string when it does not parse; there is no .env sample or config reference outside the docs; and the tutorial hard-codes SECRET_KEY='dev', overridable from instance/config.py. The technical assessment gives the reasoning per criterion.

10. Infrastructure and deployment topology

Flask is a Python web framework library (version 3.2.0.dev, requires Python 3.11 or later), not a deployed service: it is packaged with flit_core and published to PyPI, and the repository deploys nothing itself. It has no Dockerfile, no compose file, no Terraform, no Kubernetes manifests and no Procfile. The infrastructure it does run is the delivery pipeline: GitHub Actions checks every change, a tag builds and publishes the package, and Read the Docs builds the documentation. Production hosting is the application developer's choice of WSGI server. The repository holds none, and its docs/deploying/ pages (Gunicorn, Waitress, mod_wsgi, uWSGI, gevent, eventlet, ASGI, nginx, Apache httpd) describe options rather than configure any.

Environments

Four environments appear in the repository. What they share is the dependency set: uv.lock is committed, the tox environments run through uv-venv-lock-runner with frozen constraints, the CI workflows call uv run --locked, and Read the Docs installs the docs dependency group through uv. What they do not share is credentials: every workflow starts from permissions: {}, checkouts set persist-credentials: false, and only the job that uploads to PyPI is granted an OIDC token, inside the publish environment.

EnvironmentWhat runs thereShared with the othersIsolated
Developer machineThe flask run development server (werkzeug, 127.0.0.1:5000 by default), tox, pre-commit; optionally the .devcontainer on the mcr.microsoft.com/devcontainers/python:3 imageuv.lock, pyproject.toml dependency groups, .pre-commit-config.yamlEverything else; nothing in the repository reaches a developer machine except the devcontainer definition
GitHub Actions runnersThe five workflows below: tests (with its typing job), pre-commit, zizmor, lock, and the build half of publishThe lockfile and the tox configuration in pyproject.tomlEach job is a fresh hosted runner; jobs start with no token permissions and hand files on only through an uploaded artifact
publish environmentThe publish-pypi job of publish.yaml, which uploads the built distribution with PyPI trusted publishingThe single dist/ artifact built by the build jobThe only place holding id-token: write; its protection rules are set in GitHub, not in the repository
Read the DocsA Sphinx build of docs/ on Ubuntu 24.04 and Python 3.13, warnings as errors, dirhtml outputThe lockfile, through uv run --group docsRuns on Read the Docs infrastructure; what triggers a build is configured there, not in the repository

How a change and a release travel

A pull request, or a push to main or stable, runs the checks: tests.yaml (an 11-job matrix of CPython 3.11 to 3.15, free-threaded 3.14t, Windows, macOS, PyPy 3.11, minimum and development dependency versions, plus a typing job running mypy), pre-commit.yaml (ruff check, ruff format, uv-lock, codespell, pre-commit-hooks) and, when a YAML file changes, zizmor.yaml. Tests skip changes confined to docs/ and README.md. A release is a tag push: the build job runs uv build with SOURCE_DATE_EPOCH taken from the last commit and uploads dist/ as one artifact, then two jobs consume that same artifact in parallel, one creating a draft GitHub release and one publishing to PyPI. Every action is pinned to a commit SHA and every workflow starts from permissions: {}.

checks Developer machine dev server, tox, pre-commit optional .devcontainer Pull request, or push to main or stable tests.yaml 11-job matrix + mypy pre-commit.yaml ruff, codespell zizmor.yaml workflow audit Status checks on GitHub a failure is reported there release Maintainer tags a release commit Tag push any tag: tags ['*'] publish.yaml: build uv build, SOURCE_DATE_EPOCH upload dist/ as one artifact no token permissions create-release draft GitHub release publish-pypi publish environment OIDC trusted publishing PyPI pypi.org/project/Flask Application developer installs Flask, hosts it on a WSGI server (not in repo) housekeeping and docs Daily schedule cron 0 0 * * * lock.yaml locks threads idle 14 days Read the Docs trigger set outside the repo .readthedocs.yaml sphinx-build -W, dirhtml Documentation site built with the docs group
Figure 10.1 · delivery pipelineWhat the repository runs, drawn from .github/workflows/ and .readthedocs.yaml. The accented path is the release: one build, one artifact, two consumers. The dashed box is where Flask actually runs in production, which the repository does not define. Read the Docs builds are triggered by its own GitHub integration, configured outside the repository.

Pipeline files

The seven files that define where the repository's code is built, checked, published and documented. The devcontainer is the odd one: its on-create script installs requirements/dev.txt, which does not exist in the repository, and because the script runs under set -e it stops there, before pip install -e . and pre-commit install. The dependency groups that replaced the requirements files live in pyproject.toml.

FileTriggerWhat it does
.github/workflows/tests.yamlPull request; push to main or stable; ignores changes only to docs/** and README.mdRuns pytest through tox on an 11-job matrix (fail-fast off) and a separate typing job that runs mypy through tox run -e typing.
.github/workflows/pre-commit.yamlPull request; push to main or stableRuns every pre-commit hook on all files: ruff check, ruff format, uv-lock, codespell and the pre-commit-hooks set, with the hooks themselves pinned to commit SHAs.
.github/workflows/publish.yamlPush of any tagBuilds the sdist and wheel once, creates a draft GitHub release with them, and uploads them to PyPI from the publish environment with trusted publishing.
.github/workflows/zizmor.yamlPull request or push touching a YAML fileAudits the GitHub Actions workflows for security problems with zizmor and annotates findings on the change.
.github/workflows/lock.yamlDaily cron at 00:00 UTCLocks closed issues, pull requests and discussions with no activity for 14 days; the only workflow granted write access to them.
.readthedocs.yamlRead the Docs build (trigger configured on Read the Docs)Installs uv on Ubuntu 24.04 with Python 3.13 and runs sphinx-build -W -b dirhtml on docs/ with the docs dependency group.
.devcontainerCreating a dev container (VS Code, Codespaces)Starts from mcr.microsoft.com/devcontainers/python:3, creates .venv and tries to install requirements/dev.txt, a file that does not exist, so setup halts at that line.

Infrastructure and packaging files probed

The evidence probes 26 standard paths. Two are present: .github/workflows and pyproject.toml. The 24 absent ones say as much: no container, no infrastructure as code, no process manager, no other CI system and no .env sample, which is what a library that is installed rather than deployed looks like.

Infrastructure and packaging paths probed 26 rows
PathPresentWhat that means here
DockerfilenoNo container image is built.
docker-compose.ymlnoNo local multi-service stack; the celery example's Redis is started by hand.
compose.ymlnoAs above.
serverless.ymlnoNo serverless deployment.
template.ymlnoNo AWS SAM or CloudFormation template.
template.yamlnoAs above.
samconfig.tomlnoNo SAM deployment configuration.
main.tfnoNo Terraform.
terraformnoNo Terraform directory.
cdk.jsonnoNo AWS CDK app.
ProcfilenoNo process definition for a platform host.
MakefilenoTasks run through tox environments in pyproject.toml instead.
k8snoNo Kubernetes manifests.
.github/workflowsyesThe five workflows in the table above: the only automation the repository runs.
.gitlab-ci.ymlnoGitHub Actions is the only CI.
JenkinsfilenoAs above.
azure-pipelines.ymlnoAs above.
.env.examplenoNo environment sample; section 9 covers configuration.
.env.samplenoAs above.
composer.jsonnoNo PHP.
package.jsonnoNo Node tooling; the javascript example loads its scripts in templates.
pyproject.tomlyesPackage metadata, the flit_core build backend, the flask console script, dependency groups and the tox environments CI runs.
go.modnoNo Go.
Cargo.tomlnoNo Rust.
pom.xmlnoNo Java.
.gitattributesnoNo line-ending or export rules.

11. Data and persistence

The framework itself keeps no server-side store. The one piece of state Flask persists between requests is the session, and it lives in the client, in a signed (not encrypted) cookie named session; its signing, age limit, key rotation and the NullSession used when no SECRET_KEY is set are described in section 8 (src/flask/sessions.py:83-97, src/flask/sessions.py:276-385). The two other stores in the repository belong to the example applications: the tutorial example stores data in SQLite at instance/flaskr.sqlite, and the celery example points Celery at Redis on redis://localhost as both broker and result backend; the evidence's host scan does not list it. The evidence's store probe found one file, schema.sql; the other rows below were found by reading the examples and sessions.py.

Stores

StoreOwnerWhere it livesWhat it holdsLifetime
session cookieFlask (SecureCookieSessionInterface)The visitor's browser, sent back on every request; cookie name from SESSION_COOKIE_NAME, default sessionWhatever the application puts in the session, serialised as tagged JSON and signed with the SECRET_KEY; flashed messages are kept there tooBrowser session, or PERMANENT_SESSION_LIFETIME (31 days) when the session is marked permanent; the signature's max_age rejects older cookies
flaskr.sqliteTutorial exampleA SQLite file at instance/flaskr.sqlite, path set in examples/tutorial/flaskr/__init__.py:132 tables: user (id, username UNIQUE, password hash) and post (id, author_id FK, created, title, body)Until the next flask --app flaskr init-db, which drops and recreates both tables; no retention rule
RedisCelery exampleredis://localhost, as both broker and result backend (examples/celery/src/task_app/__init__.py:11-12)Queued task messages, and the state and return value of the tasks that keep results (task_ignore_result is on by default, off for the add and process tasks)Whatever Celery and the Redis server are configured for; the example sets no expiry

Keys and indexes

The only declared schema is the tutorial's. It has primary keys, one UNIQUE constraint and one foreign key, and no index beyond those: nothing indexes post.author_id, and the blog index query orders every post by created with no index on that column either, so it reads and sorts the whole table. The foreign key is declared but SQLite enforces foreign keys only when PRAGMA foreign_keys is turned on, and the connection helper does not turn it on. The session cookie and Redis have keys but no indexes.

StoreKey or indexKindAccess pattern it serves
flaskr.sqliteuser.idINTEGER PRIMARY KEY AUTOINCREMENTLoading the logged-in user on every request from the user_id held in the session, and the join from post to its author.
flaskr.sqliteuser.usernameUNIQUE NOT NULL (an implicit index)The login lookup by username, and the duplicate check on registration, which surfaces as an IntegrityError caught in the register view.
flaskr.sqlitepost.idINTEGER PRIMARY KEY AUTOINCREMENTFetching one post to show, update or delete it.
flaskr.sqlitepost.author_idFOREIGN KEY to user.id, no index, not enforcedThe join that attaches a username to each post, and the author check before an update or delete; no query looks posts up by author, so the missing index is not yet on a path.
session cookieCookie name sessionSingle signed value per visitor, no indexRead whole and verified at the start of a request, written whole at the end if the session changed or is permanent and refreshed each request.
RedisCelery task idKey layout owned by Celery, no index in the exampleThe polling endpoint at /tasks/result/<id> reads one task's state and value by id.

Files that touch a store

Eight files read or write one of the three stores. In the framework only sessions.py does; the request context opens the session each time it is pushed for a request and the response step saves it, both through the session interface. The rest are example code.

Files that touch a store 8 rows
FileStoreFunctions that touch itWhat it does
examples/tutorial/flaskr/schema.sqlflaskr.sqlitenone (SQL script)Drops the user and post tables if they exist and creates them empty. It is the whole schema, and the only way it changes is by being re-run.
examples/tutorial/flaskr/db.pyflaskr.sqliteget_db, close_db, init_db, init_db_command, init_appOpens one SQLite connection per application context, closes it on teardown, and runs schema.sql from the init-db command. It is the only connection code in the tutorial.
examples/tutorial/flaskr/auth.pyflaskr.sqlite, session cookieload_logged_in_user, register, login, logoutInserts and reads users with inline SQL, and puts the user's id in the session at login and clears it at logout.
examples/tutorial/flaskr/blog.pyflaskr.sqliteindex, get_post, create, update, deleteLists, reads, inserts, updates and deletes posts with inline SQL in the view functions, committing after each write.
src/flask/sessions.pysession cookieopen_session, save_session, get_signing_serializerVerifies and decodes the session cookie at the start of a request, and signs and sets (or deletes) it on the response. The framework's only persistence code.
examples/celery/src/task_app/__init__.pyRediscelery_init_appConfigures Celery with Redis as broker and result backend and runs each task inside a Flask application context.
examples/celery/src/task_app/views.pyRedisresult, add, block, processQueues tasks on the broker and returns their ids, and reads a task's state and value back from the result backend.
examples/celery/src/task_app/tasks.pyRedisadd, block, processThe task bodies the worker runs; their return values and progress updates are written to the result backend.

The functions named above, one row each.

Functions that touch a store 26 rows
FunctionWhereStoreWhat it does
open_sessionsrc/flask/sessions.py:323session cookieReads the session cookie and verifies its signature and age; returns an empty session for a missing or invalid cookie, or None when there is no secret key so a NullSession is used.
save_sessionsrc/flask/sessions.py:337session cookieWrites the signed session to the response cookie with the configured cookie attributes, deletes the cookie when the session was emptied, and adds Vary: Cookie when the session was read.
get_signing_serializersrc/flask/sessions.py:303session cookieBuilds the itsdangerous serializer from the current secret key plus any fallback keys, or returns None when no secret key is set.
get_dbexamples/tutorial/flaskr/db.py:9flaskr.sqliteOpens a SQLite connection to the configured database path the first time it is called in an application context and keeps it on g for reuse.
close_dbexamples/tutorial/flaskr/db.py:23flaskr.sqliteCloses the context's connection if one was opened; registered as an application-context teardown.
init_dbexamples/tutorial/flaskr/db.py:33flaskr.sqliteRuns schema.sql against the database, dropping and recreating both tables.
init_db_commandexamples/tutorial/flaskr/db.py:42flaskr.sqliteThe init-db CLI command: calls the schema reset and prints a confirmation.
init_appexamples/tutorial/flaskr/db.py:51flaskr.sqliteRegisters the connection teardown and the init-db command on the application.
load_logged_in_userexamples/tutorial/flaskr/auth.py:33flaskr.sqlite, session cookieBefore every request, reads user_id from the session and loads that user row into g.user, or sets it to None.
registerexamples/tutorial/flaskr/auth.py:47flaskr.sqliteInserts a new user with a hashed password, reporting a taken username when the UNIQUE constraint fails.
loginexamples/tutorial/flaskr/auth.py:85flaskr.sqlite, session cookieLooks the user up by username, checks the password hash, then clears the session and stores the user's id in it.
logoutexamples/tutorial/flaskr/auth.py:113session cookieClears the session, which removes the stored user id, and redirects to the index.
indexexamples/tutorial/flaskr/blog.py:17flaskr.sqliteSelects every post joined to its author's username, newest first, and renders the list.
get_postexamples/tutorial/flaskr/blog.py:28flaskr.sqliteFetches one post with its author, aborting with 404 if it does not exist and 403 if the current user is not the author when that check is asked for.
createexamples/tutorial/flaskr/blog.py:62flaskr.sqliteInserts a post for the logged-in user after checking a title was given, then commits.
updateexamples/tutorial/flaskr/blog.py:88flaskr.sqliteLoads the post with the author check, then updates its title and body and commits.
deleteexamples/tutorial/flaskr/blog.py:115flaskr.sqliteChecks the post exists and belongs to the user, then deletes it and commits.
celery_init_appexamples/celery/src/task_app/__init__.py:29RedisCreates the Celery app from the CELERY config block (Redis broker and backend), makes every task run inside the Flask app context, and stores it in app.extensions.
resultexamples/celery/src/task_app/views.py:11RedisLooks a task up by id in the result backend and returns whether it is ready, whether it succeeded, and its value or progress.
add (view)examples/celery/src/task_app/views.py:22RedisQueues the add task with two integers from the form and returns its id.
block (view)examples/celery/src/task_app/views.py:30RedisQueues the block task and returns its id.
process (view)examples/celery/src/task_app/views.py:36RedisQueues the process task with a total from the form and returns its id.
add (task)examples/celery/src/task_app/tasks.py:8RedisReturns the sum of two integers; the result is kept in the backend.
block (task)examples/celery/src/task_app/tasks.py:13RedisSleeps five seconds; its result is not kept.
process (task)examples/celery/src/task_app/tasks.py:18RedisCounts to the given total one second at a time, writing a PROGRESS state to the backend at each step, and returns the final count.
SecureCookieSessionInterfacesrc/flask/sessions.py:284session cookieThe default session interface class: fixes the salt, SHA-1 digest, HMAC key derivation and tagged JSON serializer that the session functions above use.

Personal data

The framework holds no personal data of its own; what goes into the session is the application's choice. In this repository personal data appears only in the tutorial: usernames and password hashes (hashed with werkzeug's password hashing, never stored in plain text) in the user table, and post titles and bodies tied to their author. The session cookie holds the logged-in user_id, and because the cookie is signed and not encrypted, the visitor can read it (and any flashed message) by decoding the cookie, though not change it. The celery example's Redis holds integers and progress counts, nothing about a person. No store has a retention or deletion rule beyond the session's expiry and the tutorial's delete-post view; there is no way to delete a user.

Layers and tiers

Layers. In the framework, session persistence sits behind its own layer: the session interface is a pluggable class with an open and a save method, and an application swaps the cookie store for a server-side one by assigning a different session_interface. The tutorial has no data-access layer beyond the connection helper: SQL strings are written inline in the view functions of auth.py and blog.py, with one small shared lookup for a post. The celery example calls Celery from its views directly. There is no ORM, no repository module and no migrations anywhere; schema change in the tutorial is schema.sql dropping and recreating both tables.

Tiers. Each store is a single tier. The framework has one, the client-held cookie. The tutorial has one primary store, a single SQLite file, with no cache in front of it and no archive, search or analytics copy behind it. The celery example's Redis is a message broker and a short-lived result store, not a cache of anything. Nothing in the repository adds a cache tier, cold storage or a read replica.

Data and persistence rating

Data and persistence: 7/10, Good

Good for what the repository holds. The framework deliberately keeps no server-side store: session state is a signed, expiring cookie with a size warning at 4,093 bytes, and the tutorial store has primary keys, a UNIQUE username, a foreign key, hashed passwords and a connection closed in app-context teardown. The gaps are local and known: no data-access layer in the tutorial (SQL in view functions), no migrations, no index on post.author_id, no retention policy, and session data that is signed but not encrypted, so anything put in it is visible to the user. The technical assessment gives the reasoning per criterion.

12. External integrations

Flask is a library that runs inside its host's Python process, so almost everything it integrates with is another library loaded into that same process, not a service on the network. At run time the framework opens no connection of its own: the request arrives from the WSGI server that called it, and the response goes back the same way. The integrations fall into four groups: the six runtime libraries declared in pyproject.toml:23-30 (Werkzeug, Jinja, Click, itsdangerous, Blinker, MarkupSafe), which Flask cannot import without; the two optional extras in pyproject.toml:32-34 (asgiref for async, python-dotenv for dotenv), which switch off one feature each when absent; the back ends the example applications bring (SQLite, Redis, Celery), which are not part of the package; and the delivery services that test, document and publish it (GitHub Actions, the pre-commit hook repositories, Read the Docs, PyPI). "Down" means something different for each group, so the last column says what fails and when.

Integrations 15 rows
IntegrationKindWhere it is usedWhat it providesWhat breaks when it is down or missing
Werkzeug (werkzeug>=3.1.0)runtime librarysrc/flask/app.py, src/flask/wrappers.py, src/flask/helpers.py, src/flask/testing.pyThe WSGI toolkit underneath Flask: request and response objects, URL routing, HTTP exceptions, safe file serving, the test client and the development server.Everything: import flask fails, so no application starts. An incompatible release breaks routing and request parsing; the tests-min and tests-dev CI jobs exist to catch that at both ends of the supported range.
Jinja (jinja2>=3.1.2)runtime librarysrc/flask/templating.py, src/flask/app.pyThe template engine behind render_template, with HTML autoescaping and a compiled-template cache.import flask fails. No page that renders a template can be served.
Click (click>=8.1.3)runtime librarysrc/flask/cli.py, src/flask/app.pyThe flask command line, its options and their FLASK_ environment variables (section 9), and app.cli custom commands.import flask fails, because app.py imports the CLI module. The flask run, shell and routes commands are gone.
itsdangerous (itsdangerous>=2.2.0)runtime librarysrc/flask/sessions.pyHMAC signing and timed verification of the session cookie.import flask fails. If it signed differently after an upgrade, every existing session cookie would fail verification and users would be logged out.
Blinker (blinker>=1.9.0)runtime librarysrc/flask/signals.pyThe Namespace that holds Flask's 10 built-in signals, the hook extensions use for logging, metrics and tests.import flask fails. Extensions that subscribe to signals stop receiving them.
MarkupSafe (markupsafe>=2.1.1)runtime librarysrc/flask/json/tag.py; through Jinja's autoescapingThe Markup string type and HTML escaping; the session serializer tags Markup values so they survive the round trip.import flask fails. Autoescaping, the main defence against injected HTML in templates, depends on it.
asgiref (async extra, asgiref>=3.2)optional librarysrc/flask/app.py:1108-1143Runs an async def view to completion inside the synchronous worker, through async_to_sync.Only async views: the first call to one raises RuntimeError, "Install Flask with the 'async' extra in order to use async views." Synchronous views are unaffected.
python-dotenv (dotenv extra)optional librarysrc/flask/cli.py:493-512, src/flask/cli.py:698-763Reads .flaskenv, .env and --env-file into the environment for the CLI and Flask.run.Dotenv files are ignored with a yellow tip on stderr, so settings such as FLASK_APP kept there do not apply. An explicit --env-file stops the command with an error.
SQLiteexample back end (Python's sqlite3)examples/tutorial/flaskr/db.py, examples/tutorial/flaskr/__init__.py:13The tutorial's only store, instance/flaskr.sqlite, opened per request (section 11).The tutorial only. If the file is missing or flask init-db was never run, every page that reads posts or users fails with a database error.
Redisexample back end (network service)examples/celery/src/task_app/__init__.py:11-12Broker and result backend for the celery example, at redis://localhost.The celery example only. Submitting a task from /tasks/add, /tasks/block or /tasks/process fails, and /tasks/result/<id> cannot read results.
Celeryexample back end (worker process)examples/celery/src/task_app/__init__.py:29-39, examples/celery/src/task_app/tasks.pyRuns the example's three tasks in a separate worker process inside an application context.The celery example only. With Redis up but no worker, tasks queue and /tasks/result/<id> reports them as not ready indefinitely.
PyPIdistribution service.github/workflows/publish.yaml:46-60, pyproject.toml:1-3Where Flask is published, through trusted publishing from the protected publish environment, and where users install it from.A tagged release builds and creates the draft GitHub release but cannot upload. New installs of Flask and its dependencies fail; running applications are unaffected.
GitHub ActionsCI service.github/workflows/ (tests, pre-commit, publish, zizmor, lock)Runs the test matrix, lint and type checks, workflow audit, releases and the daily issue lock (section 10).Pull requests go unchecked and no release can be published. Nothing at run time depends on it.
Read the Docsdocumentation build service.readthedocs.yamlBuilds the Sphinx documentation with uv run --group docs sphinx-build -W.The documentation is not rebuilt; docs-only changes cannot be previewed or published. The library is unaffected.
pre-commit hook repositoriesdeveloper tooling fetched from GitHub.pre-commit-config.yaml:2-17Four hook repositories (ruff, uv, codespell, pre-commit-hooks), each pinned to a commit SHA, run locally and by the pre-commit workflow.The hooks cannot be installed, so the pre-commit check fails until GitHub is reachable. Already-cached hooks keep working locally.

Outbound calls

The evidence scanned 98 files (code, scripts, container builds, CI and manifests) and found no code that opens a connection: no HTTP client, socket, shell download or git fetch. It found 6 hosts named in non-test files, and every one is metadata, a documentation link or a docstring example; nothing in the library contacts any of them. That is what a web framework should look like: its only network peer is the client its WSGI server hands it.

HostWhere it is namedWhat forExpected?
github.com.github/ISSUE_TEMPLATE/config.yml:4, :7; .pre-commit-config.yaml:2, :7, :11, :17; pyproject.toml:78; pyproject.toml:216-221; src/flask/cli.py:708Issue-template links to the security advisory form and discussions; the four pre-commit hook repositories, fetched by pre-commit; the package's Source URL; the tests-dev tox environment's main-branch tarballs of six Pallets libraries; a python-dotenv link in a docstring.Yes. Only pre-commit and the tests-dev CI job download anything, and neither ships in the package.
flask.palletsprojects.compyproject.toml:76-77; examples/javascript/pyproject.toml:12; examples/tutorial/pyproject.toml:14; src/flask/debughelpers.py:177Documentation and changelog URLs in package metadata, and a docs link printed in the template-loading hint that explain_template_loading_attempts logs.Yes. It is text shown to a person; the code never fetches it.
discord.gg.github/ISSUE_TEMPLATE/config.yml:10; pyproject.toml:79The Pallets chat invite, as an issue-template link and the package's Chat URL.Yes. Community link only.
img.website.comsrc/flask/config.py:331, :339A placeholder value in the get_namespace docstring, showing how IMAGE_STORE_BASE_URL becomes base_url.Yes. An illustrative example inside a docstring; never executed.
palletsprojects.compyproject.toml:75The Donate URL in package metadata.Yes. Metadata only.
pypi.org.github/workflows/publish.yaml:51The URL GitHub shows for the publish deployment environment, pointing at the released version's PyPI page. The upload itself is done by pypa/gh-action-pypi-publish.Yes. Publishing to PyPI is the release process (section 10).

The other 27 hosts in the evidence's integration count are rowed below so that all 33 are accounted for. They are test fixtures, local names and documentation links. The test hosts are passed to Flask's test client as a base_url, which only builds a WSGI environ in memory, so none is ever resolved or contacted. The evidence also lists [::1] and 127.0.0.1 as local addresses in tests, outside the 33.

Other hosts named in tests, comments and documentation 27 rows
HostWhere it is namedWhat it is
a.other.testtests/test_request.py:67Test base URL for the trusted-hosts check; never contacted.
abc.example.testtests/test_basic.py:1553Test base URL for subdomain matching; never contacted.
api.example.testtests/test_blueprints.py:1037Test base URL for a blueprint subdomain; never contacted.
api.parent.example.testtests/test_blueprints.py:1056Test base URL for nested blueprint subdomains; never contacted.
bad.testtests/test_request.py:69Test base URL expected to be rejected by TRUSTED_HOSTS; never contacted.
dev.localtests/test_basic.py:1581-1595Test base URL for SERVER_NAME and scheme handling; never contacted.
docs.python.orgsrc/flask/cli.py:116 (comment); tests/test_json.py:149Links to Python documentation in a comment and a test docstring.
domain.comtests/test_testing.py:259Test URL for a client POST; never contacted.
example.comsrc/flask/app.py:1168 (docstring); tests/test_basic.py:288; tests/test_testing.py:24The reserved example domain in a url_for docstring and as a test base URL.
example.testtests/test_basic.py:1550; tests/test_request.py:65Test base URL for host and subdomain matching; never contacted.
foo.dev.localtests/test_basic.py:1606Test base URL for a subdomain under SERVER_NAME; never contacted.
foo.localhosttests/test_basic.py:1599Test base URL for a subdomain of localhost; never contacted.
foo.localhost.localdomaintests/test_reqctx.py:82Expected url_for output in a subdomain test.
jinja.palletsprojects.comREADME.md:18Documentation link to Jinja in the README.
localhosttests/test_appctx.py:18; tests/test_basic.py:1369; tests/test_helpers.py:109; examples/celery/README.md:25The test client's default host, expected in generated URLs, and the address the celery README tells a reader to open.
localhost.localdomaintests/test_basic.py:1796; tests/test_reqctx.py:76Test SERVER_NAME for URL building; never contacted.
mitsuhiko.localhost.localdomaintests/test_basic.py:1812, :1825Test base URL for subdomain routing; never contacted.
parent.example.testtests/test_blueprints.py:1059Test base URL for a parent blueprint subdomain; never contacted.
raw.githubusercontent.comREADME.md:1The Flask logo image in the README, loaded by whoever renders the README (GitHub, PyPI), not by the code.
test.localhost.localdomaintests/test_basic.py:1799Test base URL for subdomain matching; never contacted.
werkzeug.palletsprojects.comREADME.md:17Documentation link to Werkzeug in the README.
wsgi.readthedocs.ioREADME.md:16Link explaining WSGI in the README.
www.example.comtests/test_basic.py:316, :336, :346Test SERVER_NAME and base URL for session cookie domain tests; never contacted.
www.localhost.localdomaintests/test_basic.py:1849Test base URL for subdomain routing; never contacted.
www.python.orgtests/test_helpers.py:15PEP 519 link in a test docstring.
xxx.example.comtests/test_testing.py:131Expected request URL in a test-client test; never contacted.
xyz.other.testtests/test_basic.py:1557Test base URL for subdomain matching; never contacted.

Install hooks. The evidence found none, and that is right: Flask builds with flit_core (pyproject.toml:84-86), a backend that runs no project code on install, and the repository has no setup.py or package lifecycle script.

Risk-pattern lines. The evidence found none: no remote script piped to a shell, encoded payload, run-time code from a string, disabled TLS check, paste or tunnel host, raw public IP or credential read. Three things a careful reader would still look for are explained here, each benign.

The tests-dev tox environment (pyproject.toml:210-227) installs main-branch tarballs of Blinker, Click, itsdangerous, Jinja, MarkupSafe and Werkzeug from github.com. This is by design: the "Development Versions" CI job tests Flask against its dependencies' unreleased code. Those downloads are unpinned, but they run only in that one CI job and are never part of what Flask ships.

shell_command runs the file named by PYTHONSTARTUP through eval (src/flask/cli.py:1019-1022). This mirrors what the interactive Python interpreter does with the same variable: it executes the developer's own startup file in their own shell session, and only when the file exists. In the same way, from_pyfile executes a configuration file the application names (src/flask/config.py:209), which is what makes a Python config file work.

The scan missed one network address: the celery example sets redis://localhost as its broker and result backend (examples/celery/src/task_app/__init__.py:11-12). It is a local address in an example application, not in the package, and the integrations table above carries it as Redis.

Functions named in this section

FunctionWhereWhat it does
render_templatesrc/flask/templating.py:136Loads a Jinja template by name and renders it with the given context plus Flask's globals. Sends the template signals around the render.
async_to_syncsrc/flask/app.py:1122Wraps a coroutine function with asgiref's async_to_sync so a synchronous worker can call it. Raises RuntimeError when the async extra is not installed.
explain_template_loading_attemptssrc/flask/debughelpers.py:124Logs, at info level, every loader Flask tried when looking up a template and whether each found it. Runs when EXPLAIN_TEMPLATE_LOADING is on.
get_namespacesrc/flask/config.py:323Returns the config keys that start with a prefix as a new dictionary, by default lower-cased and with the prefix removed.
shell_commandsrc/flask/cli.py:1000The flask shell command: opens an interactive Python shell inside the application context, after running the PYTHONSTARTUP file if one is set.
evalPython built-in, called at src/flask/cli.py:1022Executes compiled code in a given namespace. Here it runs the developer's startup file into the shell's namespace.
from_pyfilesrc/flask/config.py:187Executes a Python file as a throwaway module and copies its upper-case names into the config.

13. Error handling and resilience

Flask has one exception strategy, and every request runs through it. A view, a before-request function or the router raises. full_dispatch_request catches the exception and passes it to handle_user_exception. That function sends a Werkzeug HTTPException (a 404, a 405, an explicit abort with 403) to handle_http_exception, unless TRAP_HTTP_EXCEPTIONS says to treat it as an ordinary error. Any other exception goes to the handler registered for its class through the error-handler decorator, found by walking the exception's MRO, first on the blueprints the request matched and then on the app. If no handler matches, handle_user_exception re-raises, and the exception reaches the outer except in wsgi_app, which calls handle_exception.

handle_exception is the single place an unhandled error ends up. It always sends the got_request_exception signal. When PROPAGATE_EXCEPTIONS is true, or is left at its default of None while the app is in debug or testing mode, it re-raises so the debugger or the test runner sees the original traceback. Otherwise it logs the exception through log_exception, wraps it in an InternalServerError with original_exception set, gives that to any handler registered for 500, and builds the response through finalize_request in safe mode (from_error_handler=True). In safe mode, if an after-request function or the request_finished signal fails while the error response is being built, the failure is logged and the 500 still goes out, so a broken after-request hook cannot hide the original error.

Teardown runs whatever happens. wsgi_app pushes the context inside a try and calls the context's pop in its finally, passing it the error if there was one. A bare except: records a BaseException such as KeyboardInterrupt and re-raises it, so teardown still sees it. pop runs the request teardown functions, closes the request, runs the app-context teardown functions and sends appcontext_popped, each inside a _CollectErrors guard. One failing teardown therefore does not skip the rest, and raise_any raises everything collected as one BaseExceptionGroup at the end.

The handler functions

FunctionWhereWhat it does
handle_user_exceptionsrc/flask/app.py:880Takes any exception raised during dispatch. It sends HTTP exceptions to handle_http_exception, calls the handler registered for any other exception's class, and re-raises when none is registered.
handle_http_exceptionsrc/flask/app.py:841Returns proxy exceptions with no code, and routing redirects, unchanged. Otherwise it calls the handler registered for the status code or class, or returns the exception itself as the error response.
handle_exceptionsrc/flask/app.py:916Handles an exception that no handler took. It sends got_request_exception and then either re-raises (propagate mode) or logs and returns a 500 through any registered 500 handler.
log_exceptionsrc/flask/app.py:973Writes the unhandled exception, with its traceback, to the app logger at error level as Exception on <path> [<method>].
finalize_requestsrc/flask/app.py:1056Turns a view's or error handler's return value into a response, runs the after-request processing and sends request_finished. In safe mode it logs a failure in that processing instead of raising it.

What surfaces and what is swallowed

A visitor sees one of three things. An HTTP error comes back as its status page, or as whatever the application's handler returns. An unhandled error comes back as a generic 500 with no detail, and its traceback goes to the log. In debug mode the error propagates to Werkzeug's interactive debugger instead. A session cookie that fails its signature check, or has expired, is not reported to anyone: open_session catches BadSignature and starts an empty session, so a tampered cookie and a stale one both look like a visitor who is not logged in. On the command line, a failure to find or import the application is caught as NoAppException and printed as a message, not a traceback.

The evidence counted 164 error-handling matches across 32 files. Most are raise statements that reject misuse at setup time (a dot in a blueprint name, a setup method called after the first request, a resource opened for writing). Only 3 handlers are empty, and each one is deliberate:

Enclosing functionHandler atWhat it doesWhat is swallowed, and why it is deliberate
shell_commandsrc/flask/cli.py:1035Starts an interactive Python shell inside the application context, with the shell context processors' names already imported.An ImportError for readline or rlcompleter, which some platforms (Windows) do not ship. The shell still works without tab completion.
routes_commandsrc/flask/cli.py:1097Prints a table of every registered URL rule with its endpoint, methods, optional domain and path, sorted by the column requested.A ValueError when the requested sort key has no column in the table: match, or domain when no rule has a domain. The rows then keep the URL map's order, which for match is the intended result.
from_prefixed_envsrc/flask/config.py:163Loads every environment variable that starts with a prefix (default FLASK_) into config, parsing each value as JSON by default, and uses double underscores to set nested keys.Any exception from parsing the value, so a value that is not JSON is kept as a plain string. The comment and the docstring both say so.

Other functions this section names

FunctionWhereWhat it does
full_dispatch_requestsrc/flask/app.py:1023Sends request_started, runs the before-request functions and then the view, and sends any exception to handle_user_exception. It then finalises the result into a response.
wsgi_appsrc/flask/app.py:1627The WSGI application proper: it builds and pushes the context, dispatches, falls back to handle_exception, and pops the context in a finally block.
popsrc/flask/ctx.py:446Pops the active AppContext. On the final pop of a nested push it runs every teardown function and the popped signal, collecting their errors and raising them together.
_CollectErrorssrc/flask/helpers.py:654A context manager that records and silences any exception raised inside it, so that a series of teardown steps all run.
raise_anysrc/flask/helpers.py:676Raises every error a _CollectErrors recorded as one BaseExceptionGroup with the given message, or does nothing if there were none.
open_sessionsrc/flask/sessions.py:323Reads the session cookie and verifies its signature and age with the signing serializer. A missing, tampered or expired cookie gives an empty session.

Retries, timeouts, idempotency and dead letters

Retries: none in the framework, which makes no outbound calls to retry.

Timeouts: none in the framework; request timeouts belong to the WSGI server that runs the application.

Idempotency: no idempotency keys or deduplication; whether a repeated request is safe is up to the application's views.

Dead letters and circuit breakers: none; there is no queue or downstream service in the framework to isolate.

The one place in the repository where these would apply is the celery example. Its tasks (add, block, process in examples/celery/src/task_app/tasks.py) are declared with no autoretry_for, retry policy or time limit, so they run with Celery's defaults.

FunctionWhereWhat it does
addexamples/celery/src/task_app/tasks.py:8A Celery task that returns the sum of two integers, with its result stored in the Redis backend.
blockexamples/celery/src/task_app/tasks.py:13A Celery task that sleeps for five seconds and returns nothing, to show work that runs outside the request.
processexamples/celery/src/task_app/tasks.py:18A Celery task that counts to a total one second at a time, reporting a PROGRESS state after each step so the page can poll it.

Error handling and resilience rating

Error handling and resilience: 8/10, Good

Good. The whole request path follows one error strategy: registered handlers for HTTP and user exceptions, and a single handle_exception that signals, logs and returns a 500, or re-raises under PROPAGATE_EXCEPTIONS. Safe mode in finalize_request keeps the original error visible, teardown always runs in a finally block, and the context's pop raises all of its teardown errors together. The only 3 empty handlers are commented and harmless. Retries, timeouts, idempotency and dead letters are absent, which is correct for a framework that makes no outbound calls. The celery example sets no retry policy, and it is the one place where one would apply.

14. Availability and recovery

Flask keeps no shared server-side state: each request builds its own context, and the only state carried between requests travels in the visitor's session cookie. Any number of worker processes, on any number of machines, can serve the same application with the same SECRET_KEY, and one can replace another without losing anything. Availability is therefore a property of the deploying application's WSGI server and of whatever stores that application adds, not of this repository. That is correct for a library, and it is why the usual questions have one-line answers here:

Single points of failure

Five single points of failure do appear in what the repository designs or ships. The first is in the framework and reaches every application built on it; the second is the framework's own development server; the third is the release path; the last two belong to the example applications.

Single point of failureWhereWhat failsRecovery the repository provides
SECRET_KEYsrc/flask/sessions.py:303-321One key signs every session. If it is lost or changed without the old value listed in SECRET_KEY_FALLBACKS, every existing cookie fails verification and every visitor is logged out at once. If it is unset, the session becomes a NullSession and any write raises RuntimeError.Key rotation through SECRET_KEY_FALLBACKS, tried after the current key. Where the key is kept and backed up is the application's concern.
development serversrc/flask/cli.py:945-952The development server (werkzeug run_simple) defaults to 127.0.0.1:5000, threaded, with the reloader and interactive debugger on only in debug mode; the run command's docstring says it is for development only. It is one process with no supervisor, so an application served this way stops when that process does.None, by design: the docstrings of the run command and of the app's run method send production use to a WSGI server, and docs/deploying/ lists them.
PyPI.github/workflows/publish.yamlPyPI is the only distribution channel. If it is unavailable, no one can install or upgrade Flask from it, and a release cannot be published.The draft GitHub release holds the same built files, so a release's artifacts survive a failed upload. Rolling back a bad release is not written down beyond PyPI's own yank.
flaskr.sqliteexamples/tutorial/flaskr/db.pyThe tutorial keeps all users and posts in one SQLite file in the instance folder. Losing or corrupting it loses all of its data, and the init-db command deliberately drops and recreates both tables.None: no backup, copy or export is written. It is a teaching example.
Redisexamples/celery/src/task_app/__init__.pyThe celery example uses one Redis on redis://localhost as both broker and result backend. If it is down, tasks cannot be queued and results cannot be polled.None: no retry policy, fallback broker or second instance is configured.

The functions behind the first two rows:

FunctionWhereWhat it does
get_signing_serializersrc/flask/sessions.py:303Builds the session serializer from the current secret key, with any fallback keys listed in SECRET_KEY_FALLBACKS accepted for verification; returns None when no secret key is set.
open_sessionsrc/flask/sessions.py:323Verifies the session cookie against those keys and its maximum age; a cookie that fails verification yields a fresh, empty session rather than an error.
run_commandsrc/flask/cli.py:934The flask run command: loads the application and serves it with werkzeug's development server, turning the reloader and debugger on only in debug mode unless told otherwise.

Release recovery and deployment safety

A tag push triggers publish.yaml. The build job runs once and uploads one artifact; the GitHub release is created as a draft from that artifact, and the PyPI upload runs from the protected publish environment through trusted publishing, so no long-lived PyPI token exists to be lost or leaked. What happens after a bad release is not written down: there is no rollback step and no runbook, and recovery would be PyPI's yank plus a new tag. The workflow's concurrency group is publish-${{ github.event.push.ref }}; a push event carries its ref at github.event.ref, not under a push key, so the expression is empty and every tag shares the one group publish-, with cancel-in-progress: true. Two tags pushed close together would therefore cancel the first run, which matters only if that run had not yet reached PyPI.

Detection is CI notification alone. A failing check is shown on the pull request or commit and GitHub notifies whoever pushed it; nothing in the repository monitors PyPI, the documentation site or a deployed application (section 16).

Availability and recovery rating

Availability and recovery: 7/10, Good

Good for a library. The design keeps no shared server-side state, so any number of workers can serve one application and replace each other, and the release path is guarded: one build, one artifact, a draft GitHub release and trusted publishing from a protected environment. The known gaps are no rollback written down beyond PyPI's yank, no detection beyond CI notifications, and one SECRET_KEY whose loss or change without a fallback ends every session; HA, backup, RTO and RPO belong to the deploying application and are, correctly, not stated. The technical assessment gives the reasoning per criterion.

15. Performance and scale

Flask does a small, fixed amount of work per request and then hands over to the application's view. It holds no shared server-side state, so it scales the way a WSGI application scales: the server runs more worker threads or processes, and each worker handles one request at a time. Five paths run on every request, or on every request of a common kind. They are listed below with what each one costs. The framework does no I/O of its own on any of them except reading static files from disk.

Hot paths

Hot pathWhereWhat runsCost per request
Request dispatch through wsgi_appsrc/flask/app.py:1627Builds the request and the AppContext, pushes it, runs the before-request functions, the view and the after-request functions, then pops the context and runs teardown.A context object and a contextvar set and reset, plus one call per registered hook. Blueprint hooks are looked up by the blueprints the request matched.
URL matching in match_requestsrc/flask/ctx.py:405Asks the Werkzeug map adapter to match the path and method against the URL map.Werkzeug compiles the rules once, and since Werkzeug 2.2 it matches with a state machine, so the cost grows with the number of path segments rather than the number of rules.
Session signing in open_session and save_sessionsrc/flask/sessions.py:323, src/flask/sessions.py:337Verifies the cookie's HMAC and age and decodes its JSON payload, then on the way out serialises and signs the session again if it changed or is permanent and refreshed.An HMAC-SHA1 check per request that carries a cookie. A new serializer is built on every call, and with SECRET_KEY_FALLBACKS set, a cookie signed with an old key is tried against each fallback in turn.
Template rendering through render_templatesrc/flask/templating.py:136Looks the template up in the Jinja environment, adds the context processors' values, sends the two template signals and renders.Jinja compiles a template once and caches it, and outside debug mode it does not check the template file for changes (TEMPLATES_AUTO_RELOAD follows debug). Rendering cost is the template's own.
The async view bridge through async_to_syncsrc/flask/app.py:1122ensure_sync wraps every async def view, handler and signal receiver with asgiref's async_to_sync, which drives the coroutine to completion.An event loop round trip per async call, and the worker thread is blocked until it finishes. An async view therefore uses a worker exactly as a sync view does.

The session is not opened lazily (section 5), though the AppContext docstring at src/flask/ctx.py:295-297 says it is loaded the first time it is accessed. push calls _get_session unconditionally whenever the context has a request (src/flask/ctx.py:436-440, with the comment "Open the session at the moment that the request context is available"). So open_session runs, and the cookie is verified, on every request whether or not the view touches the session. What is lazy is the response side: save_session writes a cookie only when the session is non-empty and modified, or permanent and refreshed (src/flask/sessions.py:233-247).

Concurrency model

One request runs on one thread or process for its whole life. Per-request state (the app, g, the request and the session) lives on one AppContext held in a ContextVar (_cv_app, src/flask/globals.py:40), so threads, greenlets and the asgiref event loop each see their own context and no locks are needed. The development server runs threaded by default: Flask.run sets threaded=True and the flask run option --with-threads defaults to on (src/flask/app.py:752, src/flask/cli.py:911). Production concurrency is whatever worker model the deploying application gives its WSGI server, which this repository does not configure. Async views add no concurrency inside a request handler, because each one is driven to completion on the worker that called it.

Caching

The framework caches two things. Jinja caches compiled templates in the environment, and static and send_file responses carry a cache lifetime taken from SEND_FILE_MAX_AGE_DEFAULT, through get_send_file_max_age. That key defaults to None, so browsers revalidate with conditional requests (ETag and Last-Modified) instead of caching for a fixed time. Nothing else is cached: there is no response cache, no cached session store and no memoisation of view results. Those are left to extensions or a proxy in front of the server.

Known limits

Config keyDefaultRead atWhat happens at the limit, and when it bites
MAX_CONTENT_LENGTHNone (no limit)src/flask/wrappers.py:86No limit on request body size. A large upload is read for as long as the client keeps sending, unless the WSGI server or a proxy caps it. This bites on the first oversized or slow upload, not at any load level.
MAX_FORM_MEMORY_SIZE500,000 bytessrc/flask/wrappers.py:113A non-file form field larger than this is rejected with 413 Request Entity Too Large. File parts are not counted, because Werkzeug spools them to temporary files.
MAX_FORM_PARTS1,000src/flask/wrappers.py:140A multipart body with more parts than this is rejected with 413, which caps the parser's work on a hostile form.
MAX_COOKIE_SIZE4,093 bytessrc/flask/wrappers.py:252Werkzeug warns when a Set-Cookie header is larger than this but still sends it. Browsers drop a cookie over about 4 KB, so a session that grows past it is silently lost on the client.
SEND_FILE_MAX_AGE_DEFAULTNonesrc/flask/app.py:380Static files get no fixed cache lifetime, so every page view revalidates each asset with a conditional request that usually ends in a 304. The cost grows with traffic and asset count unless a proxy or CDN serves the static files.

There is no benchmark, load test, profiling harness or stated load level anywhere in the repository. The test suite checks behaviour, not throughput, so none of the per-request costs above has a measured figure.

Functions this section names

FunctionWhereWhat it does
wsgi_appsrc/flask/app.py:1627The WSGI application proper: it builds and pushes the request context, dispatches, handles unhandled errors and pops the context in a finally block.
pushsrc/flask/ctx.py:416Makes the AppContext the active one in the contextvar and sends appcontext_pushed. For a request it opens the session and matches the URL.
_get_sessionsrc/flask/ctx.py:381Opens the session through the app's session interface if it is not open yet, falling back to a null session when the interface returns none.
match_requestsrc/flask/ctx.py:405Matches the request against the URL map and stores the matched rule and view arguments on the request, or the routing exception to raise later.
open_sessionsrc/flask/sessions.py:323Reads the session cookie and verifies its signature and age with the signing serializer. A missing, tampered or expired cookie gives an empty session.
save_sessionsrc/flask/sessions.py:337Writes the signed session back as a cookie with the configured flags when it should be set, deletes it when the session was emptied, and adds Vary: Cookie when the session was accessed.
get_signing_serializersrc/flask/sessions.py:303Builds an itsdangerous URLSafeTimedSerializer from the secret key and its fallbacks, with the cookie-session salt and HMAC-SHA1. It returns None when no secret key is set.
render_templatesrc/flask/templating.py:136Loads a template by name (or the first of a list that exists) from the app's Jinja environment and renders it with the given context plus the context processors' values.
ensure_syncsrc/flask/app.py:1108Returns a plain function unchanged and wraps a coroutine function with async_to_sync, so a sync WSGI worker can call either.
async_to_syncsrc/flask/app.py:1122Wraps a coroutine function with asgiref's async_to_sync so it runs to completion when called. It raises RuntimeError if the async extra is not installed.
get_send_file_max_agesrc/flask/app.py:363Returns the cache lifetime in seconds for a file sent by send_file, taken from SEND_FILE_MAX_AGE_DEFAULT, or None for conditional requests.
Flask.runsrc/flask/app.py:641Starts Werkzeug's development server for the app, on 127.0.0.1:5000 by default, threaded, with the reloader and debugger on only in debug mode. Called from inside flask run, it prints a warning and returns without starting a second server.
send_filesrc/flask/helpers.py:417Sends a file or file-like object to the client with its MIME type, conditional-request headers and cache lifetime, through Werkzeug's implementation.

Performance and scale rating

Performance and scale: 6/10, Fair

Fair. The design is sound and cheap per request: per-request state in a contextvar, routing compiled by Werkzeug, Jinja's template cache, and form limits of 500,000 bytes in memory and 1,000 parts. The session, though, is opened and verified on every request, not lazily. The repository has no benchmark, load test or stated load level, and MAX_CONTENT_LENGTH is unset by default, so request bodies are unbounded unless the server limits them. Each async view call goes through async_to_sync inside a sync worker, so async views gain no concurrency, which the docs state but nothing measures.

16. Observability

Flask emits one observability signal itself: logging. It does not decide where the log goes. It writes to the WSGI server's error stream, and from there it is the deploying application's and the server's choice. The other five signals the evidence probes for are absent from the framework by design, and the 10 built-in blinker signals in src/flask/signals.py are the hook an extension uses to add them. The table reproduces the evidence's signal table in full, one row per signal.

SignalPresentMatchesFilesWhere it goes and what it covers
Loggingyes85The app logger, named after the application's import name, created by create_logger. If nothing else in the logging tree handles its level, Flask adds a stream handler that writes [time] LEVEL in module: message to wsgi.errors during a request (whatever the server does with its error stream) or to sys.stderr otherwise. It covers unhandled request exceptions (log_exception, error level, with traceback), failures in finalising an error response (finalize_request), and template-loading explanations when EXPLAIN_TEMPLATE_LOADING is on. 4 of the 8 matches are in the source (src/flask/app.py:989, src/flask/app.py:1087, src/flask/debughelpers.py:179, src/flask/logging.py:71); the other 4 are in tests.
Metricsno00Absent. No request counts, latencies or error rates are recorded. An extension can build them from request_started, request_finished and got_request_exception.
Tracingno00Absent. No spans or trace-context propagation; WSGI middleware wrapped around wsgi_app is the documented place to add it.
Error reportingno00Absent. No error-tracking client is wired in. got_request_exception is sent for every unhandled exception, so a reporter can subscribe to it.
Alertingno00Absent. Nothing in the repository pages anyone about a running application.
Health checksno00Absent. The framework registers no health or readiness route, and none of the three examples defines one.

Functions this section names

FunctionWhereWhat it does
create_loggersrc/flask/logging.py:58Gets the logger named after the app, sets it to debug level when the app is in debug mode and no level is set, and adds the default stream handler only if nothing in the logging tree already handles its level.
wsgi_errors_streamsrc/flask/logging.py:16A proxy that resolves to the request's wsgi.errors stream while a request is active and to sys.stderr otherwise. The default handler writes to it.
log_exceptionsrc/flask/app.py:973Writes an unhandled exception, with its traceback, to the app logger at error level as Exception on <path> [<method>].
finalize_requestsrc/flask/app.py:1056Turns a return value into a response and runs the after-request processing. When it is building an error response, it logs a failure in that processing with logger.exception instead of raising it.
explain_template_loading_attemptssrc/flask/debughelpers.py:124Logs at info level each loader tried for a template and what it found, and hints at a misplaced template when nothing matched. It runs only when EXPLAIN_TEMPLATE_LOADING is on.
wsgi_appsrc/flask/app.py:1627The WSGI application proper: it builds and pushes the request context, dispatches, handles unhandled errors and pops the context in a finally block. Middleware wraps it.

Who would notice a failure

In a deployed application, the operator notices, through whatever reads the WSGI server's error stream. Flask's part ends at writing the line: a 500 goes to the visitor as a generic error page and the traceback goes to the log. If no one ships that log anywhere or watches it, the first person to notice is a visitor, and how long that takes depends entirely on the deploying application. Logs exist and nothing in this repository reads them. That is a design fact for a library, not an omission in one service.

In the repository's own delivery, a failed GitHub Actions workflow (tests, pre-commit, zizmor or publish) marks the commit or pull request red and notifies the committer on GitHub, so a broken build is seen within the minutes the workflow takes. Nothing watches the published package after it reaches PyPI.

17. Redundant code

The evidence listed 8 candidates: 6 groups of duplicate bodies and 2 functions whose name appears only at their definition. Each was checked against the source and a whole-repository search (grep -rn over src, tests, docs and examples). Three survive as code that could be deleted without changing what Flask does: two in the library and one in the test suite. The other five are deliberate or public, and are listed with the reason they stay.

Of the four test-only duplicate groups, three are independent test fixtures, but test_teardown_request_handler_debug_mode (tests/test_basic.py:796-811) is a line-for-line copy of test_teardown_request_handler (tests/test_basic.py:778-793). It never sets debug mode, so it runs exactly the same test twice and covers nothing its name promises. That is why 3 items are kept, not only the 2 in the library.

Items kept

CodeFile and linesWhat it doesWhat makes it redundant
_make_timedeltasrc/flask/app.py:72-76Passes None or a timedelta through unchanged and turns an integer number of seconds into a timedelta.A copy of the identical body at src/flask/sansio/app.py:53-57, which is the one used (as the converter for PERMANENT_SESSION_LIFETIME at src/flask/sansio/app.py:225). Nothing in app.py or anywhere else calls the app.py copy. It is left over from when the logic moved into the sansio layer.
_path_is_ancestorsrc/flask/cli.py:691-695Returns whether one filesystem path is an ancestor of another, by cutting the first path's length off the second and joining the two again.No caller anywhere in the repository, and the leading underscore marks it private, so no other repository should call it either.
test_teardown_request_handler_debug_modetests/test_basic.py:796-811Registers a teardown function and a view, requests the view and asserts the response and that the teardown ran once.A verbatim copy of test_teardown_request_handler at tests/test_basic.py:778-793. Despite its name it never turns on debug mode, so deleting it loses no coverage. The alternative fix is to make it set debug mode as its name says.

Candidates rejected

CandidateWhereWhat it doesWhy it is not redundant
send_static_file (2 copies)src/flask/app.py:390-410, src/flask/blueprints.py:82-102The view behind the automatic static route. It refuses if no static folder is set, then serves the named file from it through send_from_directory with the configured cache lifetime.A documented, deliberate duplicate: both docstrings say "Note this is a duplicate of the same method in the Flask class". Flask and Blueprint share a base only in the sansio layer, which must not serve files, so neither copy has a common home to move to.
open_instance_resourcesrc/flask/app.py:445Opens a file relative to the application's instance folder, for reading or writing, with UTF-8 as the default text encoding.Public API documented in docs/config.rst:829-838 for reading instance configuration. Its callers are applications in other repositories, which the evidence's name search cannot see.
teardown_request1, teardown_request2tests/test_basic.py:819-828, tests/test_basic.py:831-840Two teardown functions that each assert they received the original ZeroDivisionError, record the call, and raise and swallow a TypeError.The test needs two registered teardown functions to show that every one of them gets the same original exception even after another has disturbed sys.exc_info(). The duplication is the point of the test.
index (in two tests)tests/test_helpers.py:289-296, tests/test_helpers.py:303-310A view that sets a session value and returns a streamed response whose generator reads it back through stream_with_context.The first is a sync view and the second an async def view. The bodies match because the test checks that the same streaming code works under both, and the signature line the comparison excludes is where they differ.
index (in two tests)tests/test_testing.py:44-47, tests/test_testing.py:59-62A view that copies the request's remote address and user agent onto g and returns an empty body.Each test defines its own view on its own app fixture. One checks the test client's default environ and the other a modified one, so the views are independent fixtures, not shared code.

Other functions this section names

FunctionWhereWhat it does
test_teardown_request_handlertests/test_basic.py:778Checks that a registered teardown function runs exactly once after a successful request and that its return value is ignored.
send_from_directorysrc/flask/helpers.py:543Sends a file from inside a given directory, using Werkzeug's safe join so a path that would escape the directory gives a 404.
stream_with_contextsrc/flask/helpers.py:63Wraps a generator so that the request context stays active while the response streams, letting the generator use the request and session globals after the view has returned.

18. What was deliberately not drawn

This document draws nine figures, each because it shows something reading the source does not: the layered call graph of the request pipeline in section 5, built only from edges in the call graph; five sequence diagrams in section 6, one per flow that crosses a process or async boundary (the WSGI request, the session cookie round trip, the async view, the development server reloader and the Celery task round trip); the AppContext lifecycle and the application setup lock as state diagrams in section 7; and the CI and release pipeline in section 10. Every other diagram type was considered and turned down, for the reasons below. A figure that only restates the code, or that has to invent structure the repository does not hold, costs the reader time and can mislead.

Absences carried into the assessment

Each of these is something the repository does not have, stated as an absence in the section named. They are design facts, most of them deliberate for a framework that leaves these choices to the application, and they are carried into the technical assessment.

This document does not judge whether any of these is a risk, how severe it is or what to do about it. Those questions go to the technical assessment: its security posture, operations, risk register and remediation roadmap.

Download