flask · Architecture
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.
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.
flask run, tests it with the test client, and chooses how to host it in production. Every security, persistence and availability decision the framework leaves open (sections 8, 11 and 14) is theirs.extensions mapping, subscribing to the 10 built-in signals, and adding flask subcommands through the flask.commands entry-point group.pyproject.toml names Pallets as maintainer). They review pull requests, run the CI, and cut releases by pushing a tag, which builds the package, drafts a GitHub release and publishes to PyPI.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.
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.
| Rating | Scale | Score |
|---|---|---|
| Engineering standards | 8/10 Good | |
| Security | 8/10 Good | |
| Configuration and secrets | 7/10 Good | |
| Data and persistence | 7/10 Good | |
| Error handling and resilience | 8/10 Good | |
| Availability and recovery | 7/10 Good | |
| Performance and scale | 6/10 Fair |
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.
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.
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__.pySECRET_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__.pyflask 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.pyflask 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/docs/deploying/ but holds no deployment of its own.docs/deploying/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.
The people here are the Pallets maintainers and contributors. This is the only journey the repository carries out itself, through its GitHub Actions workflows.
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).
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.
| Part | Kind | Trigger | Declared at | Handler | What it does |
|---|---|---|---|---|---|
| Library | Console script | flask | pyproject.toml:82, src/flask/cli.py:1121 | main | Runs the module-level FlaskGroup named flask, which parses the command line, loads the application and dispatches to the chosen command. |
| Library | Module run | python -m flask | src/flask/__main__.py:3 | main | The package's __main__ module imports the same function from cli.py and calls it, so this behaves exactly like the console script. |
| Library | CLI command | flask run | src/flask/cli.py:881 | run_command | Loads 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. |
| Library | CLI command | flask shell | src/flask/cli.py:998 | shell_command | Opens an interactive Python shell inside the application context, first running the file named by PYTHONSTARTUP and adding the app's shell-context variables. |
| Library | CLI command | flask routes | src/flask/cli.py:1047 | routes_command | Prints 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. |
| Library | Plugin commands | flask <plugin command> | src/flask/cli.py:600 | _load_plugin_commands | Once per command group, loads every command installed packages register under the flask.commands entry-point group and adds each under its entry-point name. |
| Library | WSGI callable | environ, start_response from the WSGI server | src/flask/app.py:1679 | __call__ on Flask | Lets 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. |
| Library | Development server | app.run() in application code | src/flask/app.py:641 | run on Flask | Starts 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. |
| Library | HTTP route | GET /static/<path:filename> (app) | src/flask/app.py:390 (rule added at app.py:356) | send_static_file on Flask | Serves 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. |
| Library | HTTP route | GET <blueprint static_url_path>/<path:filename> | src/flask/blueprints.py:82 (rule added at sansio/blueprints.py:324) | send_static_file on Blueprint | The 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. |
| Library | Test harness | app.test_client() | src/flask/app.py:766 | test_client | Returns 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. |
| Library | Test harness | app.test_cli_runner() | src/flask/app.py:824 | test_cli_runner | Returns a CLI runner (FlaskCliRunner by default) that invokes the app's Click commands in-process with the app already loaded. |
| Tutorial | HTTP route | GET /hello | examples/tutorial/flaskr/__init__.py:26 | hello | Returns the plain text "Hello, World!", a smoke test that the application factory works. |
| Tutorial | HTTP route | GET, POST /auth/register | examples/tutorial/flaskr/auth.py:46 | register | Shows 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. |
| Tutorial | HTTP route | GET, POST /auth/login | examples/tutorial/flaskr/auth.py:84 | login | Shows 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. |
| Tutorial | HTTP route | GET /auth/logout | examples/tutorial/flaskr/auth.py:112 | logout | Clears the session, which removes the stored user id, and redirects to the index. |
| Tutorial | HTTP route | GET / (endpoint index) | examples/tutorial/flaskr/blog.py:16 | index (blog) | Lists every post joined with its author's username, newest first, and renders the blog index page. |
| Tutorial | HTTP route | GET, POST /create | examples/tutorial/flaskr/blog.py:60 | create | Behind the login_required decorator, shows the new-post form and, on POST, inserts a post owned by the logged-in user, requiring a title. |
| Tutorial | HTTP route | GET, POST /<int:id>/update | examples/tutorial/flaskr/blog.py:86 | update | Behind login_required, loads the post (404 if missing, 403 if the user is not its author) and, on POST, updates its title and body. |
| Tutorial | HTTP route | POST /<int:id>/delete | examples/tutorial/flaskr/blog.py:113 | delete | Behind login_required, checks the post exists and belongs to the user, deletes it and redirects to the index. |
| Tutorial | CLI command | flask init-db | examples/tutorial/flaskr/db.py:41 | init_db_command | Runs schema.sql against the SQLite database, which drops and recreates the user and post tables, then prints a confirmation. |
| JavaScript | HTTP route | GET / (js defaults to fetch) | examples/javascript/js_example/views.py:8 | index (javascript) | Renders the fetch variant of the demo page, the default when no variant is named in the URL. |
| JavaScript | HTTP route | GET /<any(xhr, jquery, fetch):js> | examples/javascript/js_example/views.py:9 | index (javascript) | Renders the demo page for the named client technique, xhr, jquery or fetch, from the template of that name. |
| JavaScript | HTTP route | POST /add | examples/javascript/js_example/views.py:14 | add (javascript view) | Reads two numbers from the form, defaulting each to 0, and returns their sum as JSON. |
| Celery | HTTP route | GET / | examples/celery/src/task_app/__init__.py:19 | index (celery) | Renders the page whose buttons start the example tasks and poll their results. |
| Celery | HTTP route | GET /tasks/result/<id> | examples/celery/src/task_app/views.py:10 | result | Looks 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. |
| Celery | HTTP route | POST /tasks/add | examples/celery/src/task_app/views.py:21 | add (celery view) | Reads two integers from the form, queues the add task with them and returns the task id for polling. |
| Celery | HTTP route | POST /tasks/block | examples/celery/src/task_app/views.py:29 | block (celery view) | Queues the block task and returns its id at once, showing the web request does not wait for the work. |
| Celery | HTTP route | POST /tasks/process | examples/celery/src/task_app/views.py:35 | process (celery view) | Queues the process task with the total read from the form and returns its id. |
| Celery | Celery task | message on the Redis broker | examples/celery/src/task_app/tasks.py:7 | add (task) | Runs in the Celery worker process and returns the sum of its two arguments, stored in the result backend. |
| Celery | Celery task | message on the Redis broker | examples/celery/src/task_app/tasks.py:12 | block (task) | Sleeps for 5 seconds in the worker and returns nothing; its result is not kept. |
| Celery | Celery task | message on the Redis broker | examples/celery/src/task_app/tasks.py:17 | process (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.
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.
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.
| Module | Files | What it owns |
|---|---|---|
| src/flask | 24 | The 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. |
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).
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-package | Files | What it owns |
|---|---|---|
| src/flask | 18 | Everything 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/sansio | 3 | The 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/json | 3 | JSON 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:
| Function | Where | What it does |
|---|---|---|
jsonify | src/flask/json/__init__.py:138 | Builds 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.
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.
| From | To | Kind | Where |
|---|---|---|---|
| src/flask | src/flask/sansio | Runtime | app.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/sansio | src/flask | Runtime | sansio/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/flask | src/flask/json | Runtime | __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/json | src/flask | Runtime | json/__init__.py:6 imports current_app from ..globals. Type only in json/__init__.py:10 (..wrappers). |
| src/flask/sansio | src/flask/json | Runtime | sansio/app.py:27-28 imports DefaultJSONProvider and JSONProvider from ..json.provider. |
| src/flask/json | src/flask/sansio | Type only | json/provider.py:16 imports App under TYPE_CHECKING. |
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:
src/flask and src/flask/sansio import each other. The sansio layer is described as the I/O-free base that Flask builds on, yet sansio/app.py imports configuration, the context globals class, helpers, logging and templating from the package above it, so the base is not self-contained.src/flask and src/flask/json import each other. The package imports json for jsonify, the request and response wrappers and the session serializer, and json/__init__.py imports current_app back from ..globals so the module-level helpers can use the active application's JSON provider.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.
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.
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.
One row for every function in the figure, in layer order, with the file and line of its definition.
| Function | Layer | Where | What it does |
|---|---|---|---|
__call__ | WSGI entry | src/flask/app.py:1679 | The 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_app | WSGI entry | src/flask/app.py:1627 | The 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_request | Dispatch | src/flask/app.py:1023 | Marks 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_request | Dispatch | src/flask/app.py:1409 | Runs 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_request | Dispatch | src/flask/app.py:993 | Re-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_exception | Dispatch | src/flask/app.py:566 | Raises 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_sync | View and error handling | src/flask/app.py:1108 | Returns 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_sync | View and error handling | src/flask/app.py:1122 | Wraps 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_response | View and error handling | src/flask/app.py:1092 | Builds the automatic response to an OPTIONS request: an empty response whose Allow header lists the methods the URL accepts. |
handle_user_exception | View and error handling | src/flask/app.py:880 | Handles 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_exception | View and error handling | src/flask/app.py:841 | Looks 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_exception | View and error handling | src/flask/app.py:916 | Handles 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_exception | View and error handling | src/flask/app.py:973 | Writes the exception and traceback to the application logger at error level, with the request path and method in the message. |
finalize_request | Response | src/flask/app.py:1056 | Turns 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_response | Response | src/flask/app.py:1267 | Converts 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_response | Response | src/flask/app.py:1441 | Runs 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_context | Context and session | src/flask/app.py:1562 | Creates the AppContext for one request from the WSGI environment by calling from_environ. |
from_environ | Context and session | src/flask/ctx.py:340 | Builds 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. |
push | Context and session | src/flask/ctx.py:416 | Makes 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. |
pop | Context and session | src/flask/ctx.py:446 | Deactivates 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_session | Context and session | src/flask/ctx.py:381 | Opens 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_request | Context and session | src/flask/ctx.py:405 | Matches 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_session | Context and session | src/flask/sessions.py:323 | Reads 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_session | Context and session | src/flask/sessions.py:337 | Writes 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_serializer | Context and session | src/flask/sessions.py:303 | Builds 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. |
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.
| Flow | Boundary crossed | Functions involved | What it does |
|---|---|---|---|
| WSGI request | Network 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, pop | Turns 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 trip | Client: session state is held by the browser between requests | _get_session, open_session, get_signing_serializer, make_null_session, process_response, save_session | Verifies the signed cookie on the way in and signs the updated session on the way out; the server keeps no session store. |
| Async view | Async: a coroutine run on an event loop driven by asgiref, inside the sync worker | dispatch_request, ensure_sync, async_to_sync | Lets an async def view run under WSGI by blocking the worker thread until the coroutine finishes. |
| Development server reloader | Process: the flask CLI process spawns and replaces a child server process | make_context, run_command, load_app, run_simple, run | Serves 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 trip | Process: web process to Redis to a Celery worker process, and back by polling | add, block, process, result, celery_init_app | Moves 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. |
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.
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.
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.
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.
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.
| Function | Where | What it does |
|---|---|---|
__call__ | src/flask/app.py:1679 | The WSGI entry point the server calls. It only forwards to wsgi_app, so middleware can wrap that attribute without losing the app object. |
wsgi_app | src/flask/app.py:1627 | Creates and pushes the request's context, dispatches it, turns an unhandled exception into a response, and pops the context in a finally block. |
request_context | src/flask/app.py:1562 | Builds an AppContext carrying request data for a WSGI environ by calling from_environ. |
from_environ | src/flask/ctx.py:340 | Creates the Request object from the environ, attaches the app's JSON provider to it, and returns a new context holding it. |
push | src/flask/ctx.py:416 | Makes the context active in a contextvar, sends appcontext_pushed, opens the session and matches the URL. A nested push only increments a counter. |
pop | src/flask/ctx.py:446 | Decrements 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_context | src/flask/helpers.py:63 | Wraps 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_context | src/flask/app.py:1542 | Creates an AppContext with no request data, used for CLI commands, setup code and, in the celery example, each task. |
full_dispatch_request | src/flask/app.py:1023 | Marks the first request, sends request_started, runs before-request functions and the view, routes exceptions to the user handlers, then finalizes the response. |
preprocess_request | src/flask/app.py:1409 | Runs URL value preprocessors and before-request functions for the app and the matched blueprints; a non-None return value short-circuits the view. |
dispatch_request | src/flask/app.py:993 | Raises the routing exception if matching failed, answers automatic OPTIONS requests, and otherwise calls the matched view through ensure_sync. |
finalize_request | src/flask/app.py:1056 | Converts 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_response | src/flask/app.py:1267 | Turns any allowed view return value (string, bytes, dict, list, tuple, iterator, Response or WSGI callable) into a Response object. |
process_response | src/flask/app.py:1441 | Runs after-request functions in reverse registration order, then saves the session unless it is a null session. |
_get_session | src/flask/ctx.py:381 | Opens 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_session | src/flask/sessions.py:323 | Reads 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_serializer | src/flask/sessions.py:303 | Builds the itsdangerous serializer from SECRET_KEY and any SECRET_KEY_FALLBACKS, or returns None when there is no secret key. |
make_null_session | src/flask/sessions.py:150 | Returns a NullSession, an empty session that raises a clear error on any write because no secret key is set. |
save_session | src/flask/sessions.py:337 | Deletes, 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_sync | src/flask/app.py:1108 | Returns a plain function unchanged and wraps a coroutine function so a synchronous WSGI worker can call it. |
async_to_sync | src/flask/app.py:1122 | Wraps a coroutine function with asgiref's async_to_sync, raising a RuntimeError that asks for the async extra when asgiref is not installed. |
make_context | src/flask/cli.py:657 | Sets FLASK_RUN_FROM_CLI so app.run() becomes a no-op, and attaches the ScriptInfo that commands use to load the app. |
run_command | src/flask/cli.py:934 | The flask run command: loads the app and starts Werkzeug's development server with the host, port, reloader, debugger, threading and TLS options given. |
load_app | src/flask/cli.py:333 | Finds and imports the application from --app, FLASK_APP, a factory, or wsgi.py or app.py in the current directory. |
run_simple | werkzeug.serving | Werkzeug's development server, outside this repository; it serves a WSGI app and can run it under the reloader and the interactive debugger. |
run | src/flask/app.py:641 | Flask.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_app | examples/celery/src/task_app/__init__.py:29 | Creates 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. |
add | examples/celery/src/task_app/views.py:22 | Route 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. |
block | examples/celery/src/task_app/views.py:30 | Route that enqueues the block task, which sleeps for five seconds and keeps no result, and returns the task id. |
process | examples/celery/src/task_app/views.py:36 | Route that enqueues the process task, which reports a PROGRESS state once a second for total steps, and returns the task id. |
result | examples/celery/src/task_app/views.py:11 | Route that looks up a task id with AsyncResult and returns whether it is ready, whether it succeeded, and its value or progress. |
delay | celery (library) | Celery's shortcut for sending a task message to the broker with the given arguments; it returns an AsyncResult without waiting. |
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.
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.
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.
| Machine | From | To | Trigger | What it does |
|---|---|---|---|---|
| AppContext lifecycle | (none) | Created | from_environ (src/flask/ctx.py:340), or app_context (src/flask/app.py:1542) for a context with no request | Builds 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 lifecycle | Created | Pushed | push (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 lifecycle | Pushed | Pushed | push again, or pop while the count is above one | A nested push only increments _push_count and a non-final pop only decrements it; no signal, teardown or matching runs. |
| AppContext lifecycle | Pushed | Torn down | final 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 lifecycle | Created, or Pushed but not active | RuntimeError | pop out of turn | Refuses to pop a context that was never pushed, when no context is active, or when another context is the active one. |
| AppContext lifecycle | Torn down | Pushed | push again, by the debugger or test client | Pushes 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 lock | Setup | Serving | full_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 lock | Serving | AssertionError | setupmethod (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 lock | Serving | Setup | run (src/flask/app.py:641) returning | Flask.run starts Werkzeug's development server; when it returns, its finally block sets _got_first_request back to false. |
| Blueprint setup lock | Open | Registered | first 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. |
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.
| Boundary | What crosses it | What the framework does there |
|---|---|---|
| Browser to WSGI server to application | Untrusted HTTP: path, headers, query string, form and body | Werkzeug 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 client | All session state, round-tripped on every request | Signed 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 HTML | Values a view passes into a template | Jinja 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 system | A filename taken from the URL | Static 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 debugger | Tracebacks and, with code execution on, a Python console in the browser | Werkzeug'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 PyPI | The released package | A 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. |
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.
| Key | Default | What it governs | At the default |
|---|---|---|---|
SECRET_KEY | None | The 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_FALLBACKS | None | Older keys still accepted when verifying, for rotation | Only the current key verifies, so changing SECRET_KEY invalidates every existing session. |
SESSION_COOKIE_HTTPONLY | True | Whether page scripts can read the session cookie | Scripts cannot read it. |
SESSION_COOKIE_SECURE | False | Whether the browser sends the cookie only over HTTPS | The cookie is also sent over plain HTTP. |
SESSION_COOKIE_SAMESITE | None | The cookie's SameSite attribute | No attribute is set, so the browser applies its own default. |
TRUSTED_HOSTS | None | The Host header values the app accepts | Any Host header is accepted and used to build URLs. |
PERMANENT_SESSION_LIFETIME | 31 days | The age limit applied to every session signature, and the expiry of a permanent session's cookie | A signed cookie verifies for up to 31 days after it was last issued. |
MAX_CONTENT_LENGTH | None | The largest request body the app will read | No limit, unless the WSGI server sets one. |
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.
| Function | Where | What it does |
|---|---|---|
get_signing_serializer | src/flask/sessions.py:303 | Builds the itsdangerous serializer from SECRET_KEY, with any SECRET_KEY_FALLBACKS ahead of it, or returns None when there is no secret key. |
open_session | src/flask/sessions.py:323 | Reads 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_session | src/flask/sessions.py:337 | Deletes 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. |
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.
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.
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.
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.
| Function | Where | What it does |
|---|---|---|
make_null_session | src/flask/sessions.py:150 | Returns a NullSession, an empty session that raises a clear error on any write because no secret key is set. |
send_static_file | src/flask/app.py:390, src/flask/blueprints.py:82 | The 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_directory | src/flask/helpers.py:543 | Sends 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_command | src/flask/cli.py:1000 | The flask shell command: starts an interactive Python shell in an app context, first running the PYTHONSTARTUP file if one is set. |
register | examples/tutorial/flaskr/auth.py:47 | Tutorial view that validates a username and password and inserts the user with a Werkzeug password hash, refusing a username that already exists. |
login | examples/tutorial/flaskr/auth.py:85 | Tutorial view that checks the password against the stored hash and, on success, clears the session and stores the user's id in it. |
logout | examples/tutorial/flaskr/auth.py:113 | Tutorial view that clears the session, including the stored user id, and redirects to the index. |
load_logged_in_user | examples/tutorial/flaskr/auth.py:33 | Runs before every request; loads the user named by the session's user_id into g.user, or sets it to None. |
login_required | examples/tutorial/flaskr/auth.py:19 | Tutorial view decorator that redirects to the login page when g.user is None and otherwise calls the view. |
get_post | examples/tutorial/flaskr/blog.py:28 | Tutorial 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. |
eval | Python built-in | Executes code compiled from a string. Here it runs the developer's PYTHONSTARTUP file in the shell's namespace. |
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.
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.
| Variable | Default | Read at | Kind | When it is absent |
|---|---|---|---|---|
| FLASK_APP | none | src/flask/cli.py:453 (the -A/--app option), prefix from cli.py:585 | CLI, by click | load_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_DEBUG | unset, meaning off | src/flask/helpers.py:32 (get_debug_flag); src/flask/app.py:722 (Flask.run); written at cli.py:481 | CLI and app.run, by name | Debug 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_FILE | none | src/flask/cli.py:517 (the -e/--env-file option) | CLI, by click | Only 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_DOTENV | unset, meaning load | src/flask/helpers.py:43 (get_load_dotenv) | CLI and app.run, by name | The default dotenv files are loaded when python-dotenv is installed. Set to anything but 0, false or no, it skips them. |
| FLASK_RUN_FROM_CLI | unset | set at src/flask/cli.py:667; read at src/flask/app.py:706 | internal flag, by name | Flask.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_HOST | 127.0.0.1 | src/flask/cli.py:882 | CLI, by click | The development server binds to the loopback interface only. |
| FLASK_RUN_PORT | 5000 | src/flask/cli.py:883 | CLI, by click | The development server listens on port 5000. |
| FLASK_RUN_CERT | none | src/flask/cli.py:884-889 | CLI, by click | The 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_KEY | none | src/flask/cli.py:890-896 (validated at cli.py:828-864) | CLI, by click | Fine 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_RELOAD | none, follows debug | src/flask/cli.py:897-902, applied at cli.py:974 | CLI, by click | The reloader is on exactly when debug mode is on. |
| FLASK_RUN_DEBUGGER | none, follows debug | src/flask/cli.py:903-908, applied at cli.py:977 | CLI, by click | The interactive debugger is on exactly when debug mode is on. |
| FLASK_RUN_WITH_THREADS | true | src/flask/cli.py:909-913 | CLI, by click | The development server handles each request in its own thread. |
| FLASK_RUN_EXTRA_FILES | none | src/flask/cli.py:914-922 | CLI, by click | The reloader watches only the imported Python modules. Values are split on the OS path separator. |
| FLASK_RUN_EXCLUDE_PATTERNS | none | src/flask/cli.py:923-932 | CLI, by click | No file is excluded from triggering a reload. |
| FLASK_RUN_DEBUG | none, falls back to FLASK_DEBUG | src/flask/cli.py:995 (the run command's --debug option), callback cli.py:468-482 | CLI, by click | Debug 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_SORT | endpoint | src/flask/cli.py:1048-1057 | CLI, by click | flask routes sorts its table by endpoint name. Click rejects a value outside endpoint, methods, domain, rule and match. |
| FLASK_ROUTES_ALL_METHODS | false | src/flask/cli.py:1058 | CLI, by click | flask routes hides the automatic HEAD and OPTIONS methods. |
| PYTHONSTARTUP | unset | src/flask/cli.py:1019 | CLI, by name | flask 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_SETTINGS | none | src/flask/config.py:84, src/flask/config.py:107 (docstring) | documentation example | Nothing: 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. |
| FOO | env (from .env; .flaskenv says flaskenv) | tests/test_apps/.env:1, tests/test_apps/.flaskenv:1; asserted at tests/test_cli.py:545 | test fixture | No runtime effect. It proves .env wins over .flaskenv; if the files go, test_load_dotenv fails. |
| BAR | bar (from .flaskenv) | tests/test_apps/.flaskenv:2; asserted at tests/test_cli.py:547 | test fixture | No runtime effect. It proves a key set only in .flaskenv still loads. |
| SPAM | 1 (from .env) | tests/test_apps/.env:2; asserted at tests/test_cli.py:549 | test fixture | No runtime effect. It proves a key set only in .env loads. |
| EGGS | 2 in .env, 0 in .flaskenv; the test sets 3 | tests/test_apps/.env:3, tests/test_apps/.flaskenv:3; asserted at tests/test_cli.py:551 | test fixture | No 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:553 | test fixture | No runtime effect. It proves dotenv files are read as UTF-8. |
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.
| Loader | Where | What it does | On a missing or bad source |
|---|---|---|---|
from_envvar | src/flask/config.py:102 | Reads 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_env | src/flask/config.py:126 | Copies 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_pyfile | src/flask/config.py:187 | Executes 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_object | src/flask/config.py:218 | Loads 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_file | src/flask/config.py:256 | Opens 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_mapping | src/flask/config.py:304 | Updates 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. |
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.
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.
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: {}.
| Function | Where | What it does |
|---|---|---|
get_debug_flag | src/flask/helpers.py:28 | Returns whether debug mode is on, from FLASK_DEBUG. Unset, 0, false and no mean off. |
get_load_dotenv | src/flask/helpers.py:36 | Returns whether the default dotenv files should be loaded, which is the caller's default unless FLASK_SKIP_DOTENV says otherwise. |
load_dotenv | src/flask/cli.py:698 | Merges .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_debug | src/flask/cli.py:468 | Callback 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_callback | src/flask/cli.py:493 | Callback of -e/--env-file: refuses the option when python-dotenv is missing, otherwise calls load_dotenv with the given file and the defaults. |
make_context | src/flask/cli.py:657 | FlaskGroup's context factory: sets FLASK_RUN_FROM_CLI and creates the ScriptInfo that later loads the application. |
load_app | src/flask/cli.py:333 | Finds 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. |
run | src/flask/app.py:641 | Flask.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_command | src/flask/cli.py:934 | The flask run command: loads the application and starts the development server with the host, port, TLS, reload and thread options above. |
get_signing_serializer | src/flask/sessions.py:303 | Builds 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. |
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.
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.
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.
| Environment | What runs there | Shared with the others | Isolated |
|---|---|---|---|
| Developer machine | The 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 image | uv.lock, pyproject.toml dependency groups, .pre-commit-config.yaml | Everything else; nothing in the repository reaches a developer machine except the devcontainer definition |
| GitHub Actions runners | The five workflows below: tests (with its typing job), pre-commit, zizmor, lock, and the build half of publish | The lockfile and the tox configuration in pyproject.toml | Each job is a fresh hosted runner; jobs start with no token permissions and hand files on only through an uploaded artifact |
publish environment | The publish-pypi job of publish.yaml, which uploads the built distribution with PyPI trusted publishing | The single dist/ artifact built by the build job | The only place holding id-token: write; its protection rules are set in GitHub, not in the repository |
| Read the Docs | A Sphinx build of docs/ on Ubuntu 24.04 and Python 3.13, warnings as errors, dirhtml output | The lockfile, through uv run --group docs | Runs on Read the Docs infrastructure; what triggers a build is configured there, not in the repository |
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: {}.
.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.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.
| File | Trigger | What it does |
|---|---|---|
| .github/workflows/tests.yaml | Pull request; push to main or stable; ignores changes only to docs/** and README.md | Runs 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.yaml | Pull request; push to main or stable | Runs 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.yaml | Push of any tag | Builds 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.yaml | Pull request or push touching a YAML file | Audits the GitHub Actions workflows for security problems with zizmor and annotates findings on the change. |
| .github/workflows/lock.yaml | Daily cron at 00:00 UTC | Locks closed issues, pull requests and discussions with no activity for 14 days; the only workflow granted write access to them. |
| .readthedocs.yaml | Read 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. |
| .devcontainer | Creating 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. |
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.
| Path | Present | What that means here |
|---|---|---|
| Dockerfile | no | No container image is built. |
| docker-compose.yml | no | No local multi-service stack; the celery example's Redis is started by hand. |
| compose.yml | no | As above. |
| serverless.yml | no | No serverless deployment. |
| template.yml | no | No AWS SAM or CloudFormation template. |
| template.yaml | no | As above. |
| samconfig.toml | no | No SAM deployment configuration. |
| main.tf | no | No Terraform. |
| terraform | no | No Terraform directory. |
| cdk.json | no | No AWS CDK app. |
| Procfile | no | No process definition for a platform host. |
| Makefile | no | Tasks run through tox environments in pyproject.toml instead. |
| k8s | no | No Kubernetes manifests. |
| .github/workflows | yes | The five workflows in the table above: the only automation the repository runs. |
| .gitlab-ci.yml | no | GitHub Actions is the only CI. |
| Jenkinsfile | no | As above. |
| azure-pipelines.yml | no | As above. |
| .env.example | no | No environment sample; section 9 covers configuration. |
| .env.sample | no | As above. |
| composer.json | no | No PHP. |
| package.json | no | No Node tooling; the javascript example loads its scripts in templates. |
| pyproject.toml | yes | Package metadata, the flit_core build backend, the flask console script, dependency groups and the tox environments CI runs. |
| go.mod | no | No Go. |
| Cargo.toml | no | No Rust. |
| pom.xml | no | No Java. |
| .gitattributes | no | No line-ending or export rules. |
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.
| Store | Owner | Where it lives | What it holds | Lifetime |
|---|---|---|---|---|
| session cookie | Flask (SecureCookieSessionInterface) | The visitor's browser, sent back on every request; cookie name from SESSION_COOKIE_NAME, default session | Whatever the application puts in the session, serialised as tagged JSON and signed with the SECRET_KEY; flashed messages are kept there too | Browser session, or PERMANENT_SESSION_LIFETIME (31 days) when the session is marked permanent; the signature's max_age rejects older cookies |
| flaskr.sqlite | Tutorial example | A SQLite file at instance/flaskr.sqlite, path set in examples/tutorial/flaskr/__init__.py:13 | 2 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 |
| Redis | Celery example | redis://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 |
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.
| Store | Key or index | Kind | Access pattern it serves |
|---|---|---|---|
| flaskr.sqlite | user.id | INTEGER PRIMARY KEY AUTOINCREMENT | Loading the logged-in user on every request from the user_id held in the session, and the join from post to its author. |
| flaskr.sqlite | user.username | UNIQUE 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.sqlite | post.id | INTEGER PRIMARY KEY AUTOINCREMENT | Fetching one post to show, update or delete it. |
| flaskr.sqlite | post.author_id | FOREIGN KEY to user.id, no index, not enforced | The 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 cookie | Cookie name session | Single signed value per visitor, no index | Read 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. |
| Redis | Celery task id | Key layout owned by Celery, no index in the example | The polling endpoint at /tasks/result/<id> reads one task's state and value by id. |
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.
| File | Store | Functions that touch it | What it does |
|---|---|---|---|
| examples/tutorial/flaskr/schema.sql | flaskr.sqlite | none (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.py | flaskr.sqlite | get_db, close_db, init_db, init_db_command, init_app | Opens 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.py | flaskr.sqlite, session cookie | load_logged_in_user, register, login, logout | Inserts 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.py | flaskr.sqlite | index, get_post, create, update, delete | Lists, reads, inserts, updates and deletes posts with inline SQL in the view functions, committing after each write. |
| src/flask/sessions.py | session cookie | open_session, save_session, get_signing_serializer | Verifies 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__.py | Redis | celery_init_app | Configures Celery with Redis as broker and result backend and runs each task inside a Flask application context. |
| examples/celery/src/task_app/views.py | Redis | result, add, block, process | Queues 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.py | Redis | add, block, process | The task bodies the worker runs; their return values and progress updates are written to the result backend. |
The functions named above, one row each.
| Function | Where | Store | What it does |
|---|---|---|---|
open_session | src/flask/sessions.py:323 | session cookie | Reads 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_session | src/flask/sessions.py:337 | session cookie | Writes 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_serializer | src/flask/sessions.py:303 | session cookie | Builds the itsdangerous serializer from the current secret key plus any fallback keys, or returns None when no secret key is set. |
get_db | examples/tutorial/flaskr/db.py:9 | flaskr.sqlite | Opens 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_db | examples/tutorial/flaskr/db.py:23 | flaskr.sqlite | Closes the context's connection if one was opened; registered as an application-context teardown. |
init_db | examples/tutorial/flaskr/db.py:33 | flaskr.sqlite | Runs schema.sql against the database, dropping and recreating both tables. |
init_db_command | examples/tutorial/flaskr/db.py:42 | flaskr.sqlite | The init-db CLI command: calls the schema reset and prints a confirmation. |
init_app | examples/tutorial/flaskr/db.py:51 | flaskr.sqlite | Registers the connection teardown and the init-db command on the application. |
load_logged_in_user | examples/tutorial/flaskr/auth.py:33 | flaskr.sqlite, session cookie | Before every request, reads user_id from the session and loads that user row into g.user, or sets it to None. |
register | examples/tutorial/flaskr/auth.py:47 | flaskr.sqlite | Inserts a new user with a hashed password, reporting a taken username when the UNIQUE constraint fails. |
login | examples/tutorial/flaskr/auth.py:85 | flaskr.sqlite, session cookie | Looks the user up by username, checks the password hash, then clears the session and stores the user's id in it. |
logout | examples/tutorial/flaskr/auth.py:113 | session cookie | Clears the session, which removes the stored user id, and redirects to the index. |
index | examples/tutorial/flaskr/blog.py:17 | flaskr.sqlite | Selects every post joined to its author's username, newest first, and renders the list. |
get_post | examples/tutorial/flaskr/blog.py:28 | flaskr.sqlite | Fetches 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. |
create | examples/tutorial/flaskr/blog.py:62 | flaskr.sqlite | Inserts a post for the logged-in user after checking a title was given, then commits. |
update | examples/tutorial/flaskr/blog.py:88 | flaskr.sqlite | Loads the post with the author check, then updates its title and body and commits. |
delete | examples/tutorial/flaskr/blog.py:115 | flaskr.sqlite | Checks the post exists and belongs to the user, then deletes it and commits. |
celery_init_app | examples/celery/src/task_app/__init__.py:29 | Redis | Creates 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. |
result | examples/celery/src/task_app/views.py:11 | Redis | Looks 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:22 | Redis | Queues the add task with two integers from the form and returns its id. |
block (view) | examples/celery/src/task_app/views.py:30 | Redis | Queues the block task and returns its id. |
process (view) | examples/celery/src/task_app/views.py:36 | Redis | Queues the process task with a total from the form and returns its id. |
add (task) | examples/celery/src/task_app/tasks.py:8 | Redis | Returns the sum of two integers; the result is kept in the backend. |
block (task) | examples/celery/src/task_app/tasks.py:13 | Redis | Sleeps five seconds; its result is not kept. |
process (task) | examples/celery/src/task_app/tasks.py:18 | Redis | Counts to the given total one second at a time, writing a PROGRESS state to the backend at each step, and returns the final count. |
SecureCookieSessionInterface | src/flask/sessions.py:284 | session cookie | The default session interface class: fixes the salt, SHA-1 digest, HMAC key derivation and tagged JSON serializer that the session functions above use. |
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. 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.
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.
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.
| Integration | Kind | Where it is used | What it provides | What breaks when it is down or missing |
|---|---|---|---|---|
Werkzeug (werkzeug>=3.1.0) | runtime library | src/flask/app.py, src/flask/wrappers.py, src/flask/helpers.py, src/flask/testing.py | The 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 library | src/flask/templating.py, src/flask/app.py | The 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 library | src/flask/cli.py, src/flask/app.py | The 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 library | src/flask/sessions.py | HMAC 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 library | src/flask/signals.py | The 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 library | src/flask/json/tag.py; through Jinja's autoescaping | The 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 library | src/flask/app.py:1108-1143 | Runs 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 library | src/flask/cli.py:493-512, src/flask/cli.py:698-763 | Reads .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. |
| SQLite | example back end (Python's sqlite3) | examples/tutorial/flaskr/db.py, examples/tutorial/flaskr/__init__.py:13 | The 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. |
| Redis | example back end (network service) | examples/celery/src/task_app/__init__.py:11-12 | Broker 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. |
| Celery | example back end (worker process) | examples/celery/src/task_app/__init__.py:29-39, examples/celery/src/task_app/tasks.py | Runs 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. |
| PyPI | distribution service | .github/workflows/publish.yaml:46-60, pyproject.toml:1-3 | Where 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 Actions | CI 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 Docs | documentation build service | .readthedocs.yaml | Builds 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 repositories | developer tooling fetched from GitHub | .pre-commit-config.yaml:2-17 | Four 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. |
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.
| Host | Where it is named | What for | Expected? |
|---|---|---|---|
| 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:708 | Issue-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.com | pyproject.toml:76-77; examples/javascript/pyproject.toml:12; examples/tutorial/pyproject.toml:14; src/flask/debughelpers.py:177 | Documentation 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:79 | The Pallets chat invite, as an issue-template link and the package's Chat URL. | Yes. Community link only. |
| img.website.com | src/flask/config.py:331, :339 | A 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.com | pyproject.toml:75 | The Donate URL in package metadata. | Yes. Metadata only. |
| pypi.org | .github/workflows/publish.yaml:51 | The 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.
| Host | Where it is named | What it is |
|---|---|---|
| a.other.test | tests/test_request.py:67 | Test base URL for the trusted-hosts check; never contacted. |
| abc.example.test | tests/test_basic.py:1553 | Test base URL for subdomain matching; never contacted. |
| api.example.test | tests/test_blueprints.py:1037 | Test base URL for a blueprint subdomain; never contacted. |
| api.parent.example.test | tests/test_blueprints.py:1056 | Test base URL for nested blueprint subdomains; never contacted. |
| bad.test | tests/test_request.py:69 | Test base URL expected to be rejected by TRUSTED_HOSTS; never contacted. |
| dev.local | tests/test_basic.py:1581-1595 | Test base URL for SERVER_NAME and scheme handling; never contacted. |
| docs.python.org | src/flask/cli.py:116 (comment); tests/test_json.py:149 | Links to Python documentation in a comment and a test docstring. |
| domain.com | tests/test_testing.py:259 | Test URL for a client POST; never contacted. |
| example.com | src/flask/app.py:1168 (docstring); tests/test_basic.py:288; tests/test_testing.py:24 | The reserved example domain in a url_for docstring and as a test base URL. |
| example.test | tests/test_basic.py:1550; tests/test_request.py:65 | Test base URL for host and subdomain matching; never contacted. |
| foo.dev.local | tests/test_basic.py:1606 | Test base URL for a subdomain under SERVER_NAME; never contacted. |
| foo.localhost | tests/test_basic.py:1599 | Test base URL for a subdomain of localhost; never contacted. |
| foo.localhost.localdomain | tests/test_reqctx.py:82 | Expected url_for output in a subdomain test. |
| jinja.palletsprojects.com | README.md:18 | Documentation link to Jinja in the README. |
| localhost | tests/test_appctx.py:18; tests/test_basic.py:1369; tests/test_helpers.py:109; examples/celery/README.md:25 | The test client's default host, expected in generated URLs, and the address the celery README tells a reader to open. |
| localhost.localdomain | tests/test_basic.py:1796; tests/test_reqctx.py:76 | Test SERVER_NAME for URL building; never contacted. |
| mitsuhiko.localhost.localdomain | tests/test_basic.py:1812, :1825 | Test base URL for subdomain routing; never contacted. |
| parent.example.test | tests/test_blueprints.py:1059 | Test base URL for a parent blueprint subdomain; never contacted. |
| raw.githubusercontent.com | README.md:1 | The Flask logo image in the README, loaded by whoever renders the README (GitHub, PyPI), not by the code. |
| test.localhost.localdomain | tests/test_basic.py:1799 | Test base URL for subdomain matching; never contacted. |
| werkzeug.palletsprojects.com | README.md:17 | Documentation link to Werkzeug in the README. |
| wsgi.readthedocs.io | README.md:16 | Link explaining WSGI in the README. |
| www.example.com | tests/test_basic.py:316, :336, :346 | Test SERVER_NAME and base URL for session cookie domain tests; never contacted. |
| www.localhost.localdomain | tests/test_basic.py:1849 | Test base URL for subdomain routing; never contacted. |
| www.python.org | tests/test_helpers.py:15 | PEP 519 link in a test docstring. |
| xxx.example.com | tests/test_testing.py:131 | Expected request URL in a test-client test; never contacted. |
| xyz.other.test | tests/test_basic.py:1557 | Test 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.
| Function | Where | What it does |
|---|---|---|
render_template | src/flask/templating.py:136 | Loads 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_sync | src/flask/app.py:1122 | Wraps 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_attempts | src/flask/debughelpers.py:124 | Logs, 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_namespace | src/flask/config.py:323 | Returns the config keys that start with a prefix as a new dictionary, by default lower-cased and with the prefix removed. |
shell_command | src/flask/cli.py:1000 | The flask shell command: opens an interactive Python shell inside the application context, after running the PYTHONSTARTUP file if one is set. |
eval | Python built-in, called at src/flask/cli.py:1022 | Executes compiled code in a given namespace. Here it runs the developer's startup file into the shell's namespace. |
from_pyfile | src/flask/config.py:187 | Executes a Python file as a throwaway module and copies its upper-case names into the config. |
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.
| Function | Where | What it does |
|---|---|---|
handle_user_exception | src/flask/app.py:880 | Takes 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_exception | src/flask/app.py:841 | Returns 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_exception | src/flask/app.py:916 | Handles 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_exception | src/flask/app.py:973 | Writes the unhandled exception, with its traceback, to the app logger at error level as Exception on <path> [<method>]. |
finalize_request | src/flask/app.py:1056 | Turns 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. |
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 function | Handler at | What it does | What is swallowed, and why it is deliberate |
|---|---|---|---|
shell_command | src/flask/cli.py:1035 | Starts 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_command | src/flask/cli.py:1097 | Prints 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_env | src/flask/config.py:163 | Loads 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. |
| Function | Where | What it does |
|---|---|---|
full_dispatch_request | src/flask/app.py:1023 | Sends 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_app | src/flask/app.py:1627 | The WSGI application proper: it builds and pushes the context, dispatches, falls back to handle_exception, and pops the context in a finally block. |
pop | src/flask/ctx.py:446 | Pops 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. |
_CollectErrors | src/flask/helpers.py:654 | A context manager that records and silences any exception raised inside it, so that a series of teardown steps all run. |
raise_any | src/flask/helpers.py:676 | Raises every error a _CollectErrors recorded as one BaseExceptionGroup with the given message, or does nothing if there were none. |
open_session | src/flask/sessions.py:323 | Reads the session cookie and verifies its signature and age with the signing serializer. A missing, tampered or expired cookie gives an empty session. |
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.
| Function | Where | What it does |
|---|---|---|
add | examples/celery/src/task_app/tasks.py:8 | A Celery task that returns the sum of two integers, with its result stored in the Redis backend. |
block | examples/celery/src/task_app/tasks.py:13 | A Celery task that sleeps for five seconds and returns nothing, to show work that runs outside the request. |
process | examples/celery/src/task_app/tasks.py:18 | A 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. |
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.
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:
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 failure | Where | What fails | Recovery the repository provides |
|---|---|---|---|
| SECRET_KEY | src/flask/sessions.py:303-321 | One 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 server | src/flask/cli.py:945-952 | The 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.yaml | PyPI 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.sqlite | examples/tutorial/flaskr/db.py | The 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. |
| Redis | examples/celery/src/task_app/__init__.py | The 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:
| Function | Where | What it does |
|---|---|---|
get_signing_serializer | src/flask/sessions.py:303 | Builds 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_session | src/flask/sessions.py:323 | Verifies 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_command | src/flask/cli.py:934 | The 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. |
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).
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.
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 path | Where | What runs | Cost per request |
|---|---|---|---|
Request dispatch through wsgi_app | src/flask/app.py:1627 | Builds 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_request | src/flask/ctx.py:405 | Asks 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_session | src/flask/sessions.py:323, src/flask/sessions.py:337 | Verifies 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_template | src/flask/templating.py:136 | Looks 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_sync | src/flask/app.py:1122 | ensure_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).
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.
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.
| Config key | Default | Read at | What happens at the limit, and when it bites |
|---|---|---|---|
MAX_CONTENT_LENGTH | None (no limit) | src/flask/wrappers.py:86 | No 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_SIZE | 500,000 bytes | src/flask/wrappers.py:113 | A 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_PARTS | 1,000 | src/flask/wrappers.py:140 | A multipart body with more parts than this is rejected with 413, which caps the parser's work on a hostile form. |
MAX_COOKIE_SIZE | 4,093 bytes | src/flask/wrappers.py:252 | Werkzeug 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_DEFAULT | None | src/flask/app.py:380 | Static 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.
| Function | Where | What it does |
|---|---|---|
wsgi_app | src/flask/app.py:1627 | The WSGI application proper: it builds and pushes the request context, dispatches, handles unhandled errors and pops the context in a finally block. |
push | src/flask/ctx.py:416 | Makes the AppContext the active one in the contextvar and sends appcontext_pushed. For a request it opens the session and matches the URL. |
_get_session | src/flask/ctx.py:381 | Opens 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_request | src/flask/ctx.py:405 | Matches 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_session | src/flask/sessions.py:323 | Reads the session cookie and verifies its signature and age with the signing serializer. A missing, tampered or expired cookie gives an empty session. |
save_session | src/flask/sessions.py:337 | Writes 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_serializer | src/flask/sessions.py:303 | Builds 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_template | src/flask/templating.py:136 | Loads 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_sync | src/flask/app.py:1108 | Returns a plain function unchanged and wraps a coroutine function with async_to_sync, so a sync WSGI worker can call either. |
async_to_sync | src/flask/app.py:1122 | Wraps 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_age | src/flask/app.py:363 | Returns 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.run | src/flask/app.py:641 | Starts 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_file | src/flask/helpers.py:417 | Sends a file or file-like object to the client with its MIME type, conditional-request headers and cache lifetime, through Werkzeug's implementation. |
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.
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.
| Signal | Present | Matches | Files | Where it goes and what it covers |
|---|---|---|---|---|
| Logging | yes | 8 | 5 | The 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. |
| Metrics | no | 0 | 0 | Absent. No request counts, latencies or error rates are recorded. An extension can build them from request_started, request_finished and got_request_exception. |
| Tracing | no | 0 | 0 | Absent. No spans or trace-context propagation; WSGI middleware wrapped around wsgi_app is the documented place to add it. |
| Error reporting | no | 0 | 0 | Absent. No error-tracking client is wired in. got_request_exception is sent for every unhandled exception, so a reporter can subscribe to it. |
| Alerting | no | 0 | 0 | Absent. Nothing in the repository pages anyone about a running application. |
| Health checks | no | 0 | 0 | Absent. The framework registers no health or readiness route, and none of the three examples defines one. |
| Function | Where | What it does |
|---|---|---|
create_logger | src/flask/logging.py:58 | Gets 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_stream | src/flask/logging.py:16 | A 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_exception | src/flask/app.py:973 | Writes an unhandled exception, with its traceback, to the app logger at error level as Exception on <path> [<method>]. |
finalize_request | src/flask/app.py:1056 | Turns 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_attempts | src/flask/debughelpers.py:124 | Logs 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_app | src/flask/app.py:1627 | The 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. |
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.
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.
| Code | File and lines | What it does | What makes it redundant |
|---|---|---|---|
_make_timedelta | src/flask/app.py:72-76 | Passes 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_ancestor | src/flask/cli.py:691-695 | Returns 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_mode | tests/test_basic.py:796-811 | Registers 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. |
| Candidate | Where | What it does | Why it is not redundant |
|---|---|---|---|
send_static_file (2 copies) | src/flask/app.py:390-410, src/flask/blueprints.py:82-102 | The 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_resource | src/flask/app.py:445 | Opens 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_request2 | tests/test_basic.py:819-828, tests/test_basic.py:831-840 | Two 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-310 | A 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-62 | A 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. |
| Function | Where | What it does |
|---|---|---|
test_teardown_request_handler | tests/test_basic.py:778 | Checks that a registered teardown function runs exactly once after a successful request and that its return value is ignored. |
send_from_directory | src/flask/helpers.py:543 | Sends 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_context | src/flask/helpers.py:63 | Wraps 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. |
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.
Rejected: the module dependency diagram generated by modules.cjs is a single box. It finds one module group (src/flask, 24 files) and no cross-module edges, so there is nothing to connect. The sub-package table in section 4 says more, including the two two-way pairs below the grouping.
Rejected: a class diagram of the Scaffold, App, Flask and Blueprint inheritance would show four classes in two layers, which the section 4 sub-package table and one sentence already state. It would add nothing the source does not show.
Rejected: the only schema in the repository is the tutorial's two tables, user and post, with one foreign key between them. The section 11 key table carries that entity relationship diagram's content completely. The framework itself has no schema.
Rejected: the repository deploys nothing. Production hosting is the application developer's WSGI server, so any production deployment diagram would be invented. The release pipeline, which the repository does run, is drawn in section 10.
Rejected: the dispatch and error paths are ordinary control flow inside one process. The code is already that control-flow flowchart, and the section 5 call graph covers the structure.
Rejected: data moves only between the request, the view and the response within one process, plus the cookie and Redis hops already drawn as sequences in section 6. A data flow diagram would repeat those.
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.
src/flask or the examples..env.example and .env.sample are both probed absent.docs/config.rst.SECRET_KEY_FALLBACKS is manual.requirements/dev.txt, which does not exist.schema.sql drops and recreates its tables.post.created, which the blog index sorts by.PRAGMA foreign_keys.