# pallets/flask architecture

> Architecture diagram of the GitHub repository pallets/flask, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-09-18). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/pallets/flask
- Repository: https://github.com/pallets/flask
- Video tour (about a minute): https://gitdiagram.com/pallets/flask/video

## Overview

1. **Purpose and principal workflow.** Flask is a Python WSGI web-application framework: an HTTP client sends a request to an external WSGI server, and that server initiates the framework workflow by invoking a Flask application callable. Flask uses registered routes to select user application code, which returns a response directly or through optional template or JSON rendering, then hands the WSGI response back to the server.

2. **Components**

**External boundary and application authorship**
- **HTTP Client** — **Path:** `null` (external); initiates HTTP requests that reach the hosting WSGI server.
- **WSGI Server** — **Path:** `null` (external); invokes the Flask callable using the WSGI `environ` and `start_response` interface.
- **User Application and View Callbacks** — **Path:** `null` (external); supplies the `Flask` instance, route handlers, blueprints, configuration, and optional rendering/JSON/session use.
- **Werkzeug** — **Path:** `null` (external dependency); provides WSGI, HTTP, routing, exception, and response primitives used throughout Flask.
- **Jinja2** — **Path:** `null` (external dependency); renders templates loaded and contextualized by Flask.
- **itsdangerous** — **Path:** `null` (external dependency); supplies the timed URL-safe serializer selected by Flask’s secure-cookie session implementation.

**Framework entry points, composition, and routing**
- **Public API Facade** — **Path:** `src/flask/__init__.py`; re-exports application construction, request globals, response helpers, templates, JSON, sessions, signals, and blueprint APIs as the primary developer-facing import surface.
- **Flask WSGI Application** — **Path:** `src/flask/app.py`; implements the concrete `Flask` application, creates its Click command group and static route, and exposes the WSGI callable that delegates to `wsgi_app`.
- **Sans-IO Application Definition and Routing State** — **Path:** `src/flask/sansio/app.py`; owns application configuration, instance-path setup, URL map, endpoint-to-view-function mapping, Jinja/JSON provider setup points, and blueprint registration support.
- **Route and Error Registration Scaffold** — **Path:** `src/flask/sansio/scaffold.py`; provides decorators and registration APIs that associate user view functions and error handlers with application or blueprint state.
- **Blueprint Registration** — **Path:** `src/flask/sansio/blueprints.py`; packages deferred route, template, static, CLI, and callback registrations and applies them to an application with prefixes, subdomains, and defaults.
- **Module CLI Entry Point** — **Path:** `src/flask/__main__.py`; makes `python -m flask` invoke the framework CLI.
- **CLI Command Runtime** — **Path:** `src/flask/cli.py`; provides the command implementation used by the module entry point and the `Flask.cli` application command group; its body was not sampled.

**Request representations, rendering, and extension hooks**
- **Request and Response Wrappers** — **Path:** `src/flask/wrappers.py`; provides Flask-specific request/response types exported by the public API; implementation details were not sampled.
- **Application and Request Contexts** — **Path:** `src/flask/ctx.py`; holds context-local application/request state used by helpers and rendering; Flask and templating explicitly import its context types.
- **Template Rendering** — **Path:** `src/flask/templating.py`; builds a Jinja environment and dispatching loader across application and blueprint template folders, injects template context, and supports normal or streaming rendering.
- **Rendering Signals** — **Path:** `src/flask/signals.py`; defines extension-observable lifecycle signals, including template-render events emitted by the templating subsystem.
- **JSON Convenience API** — **Path:** `src/flask/json/__init__.py`; exposes `dump(s)`, `load(s)`, and `jsonify`, routing operations through the current application’s JSON provider when a context exists.
- **Application JSON Provider** — **Path:** `src/flask/json/provider.py`; defines replaceable serialization/deserialization behavior and produces application response objects with JSON MIME types.

**Cookie-backed state**
- **Secure Cookie Session Interface** — **Path:** `src/flask/sessions.py`; defines replaceable session storage semantics and the default mutable secure-cookie session behavior, including cookie attributes and `Vary: Cookie` handling.
- **Tagged Session Serialization** — **Path:** `src/flask/json/tag.py`; losslessly encodes supported non-standard Python values for session payloads through ordered, extensible JSON tags.

3. **Relationships**

- **HTTP Client -> WSGI Server:** sends an HTTP request; this is the external deployment boundary.
- **WSGI Server -> Flask WSGI Application:** invokes the application callable; `Flask.__call__` returns `self.wsgi_app(environ, start_response)`.
- **User Application and View Callbacks -> Public API Facade:** imports Flask construction, routing, rendering, JSON, and helper APIs; the facade re-exports these symbols.
- **Public API Facade -> Flask WSGI Application:** exposes `Flask` as the primary application class.
- **Flask WSGI Application -> Sans-IO Application Definition and Routing State:** initializes and uses inherited application state; the concrete constructor calls `super().__init__`.
- **Sans-IO Application Definition and Routing State -> Werkzeug:** maintains URL rules in Werkzeug routing structures; `add_url_rule` creates a `Rule` and adds it to `url_map`.
- **User Application and View Callbacks -> Route and Error Registration Scaffold:** registers callbacks through route and error-handler decorators.
- **Route and Error Registration Scaffold -> Sans-IO Application Definition and Routing State:** forwards route registration to `add_url_rule`; the route decorator invokes that method.
- **User Application and View Callbacks -> Blueprint Registration:** defines reusable route/resource groups for later application registration.
- **Blueprint Registration -> Sans-IO Application Definition and Routing State:** applies deferred rules to the app; setup state calls `app.add_url_rule`.
- **Flask WSGI Application -> User Application and View Callbacks:** dispatches a matched endpoint during request handling; the sampled routing state contains the endpoint-to-view-function mapping, although dispatch internals are outside the excerpt.
- **User Application and View Callbacks -> Template Rendering:** may render an HTML/template response rather than construct one directly.
- **Template Rendering -> Application and Request Contexts:** reads the active context and injects `g` and, when present, `request` into template context.
- **Template Rendering -> Jinja2:** renders or streams Jinja templates through the configured environment and loader.
- **Template Rendering -> Rendering Signals:** emits `before_render_template` and `template_rendered`.
- **User Application and View Callbacks -> JSON Convenience API:** may serialize response data through `jsonify` or JSON load/dump helpers.
- **JSON Convenience API -> Application JSON Provider:** delegates to `current_app.json` when an application context is active.
- **Application JSON Provider -> Flask WSGI Application:** creates the configured application response class for JSON output.
- **Secure Cookie Session Interface -> Tagged Session Serialization:** uses tagged JSON serialization for secure-cookie session values.
- **Secure Cookie Session Interface -> itsdangerous:** selects `URLSafeTimedSerializer` and signature-error handling for secure-cookie protection.
- **User Application and View Callbacks -> Module CLI Entry Point:** may invoke the framework through `python -m flask`.
- **Module CLI Entry Point -> CLI Command Runtime:** calls `cli.main()` directly.
- **Flask WSGI Application -> CLI Command Runtime:** creates an `AppGroup` for application-specific CLI commands.
- **User Application and View Callbacks -> Flask WSGI Application:** returns a handler result into Flask’s request lifecycle.
- **Flask WSGI Application -> WSGI Server:** completes the WSGI response after request processing.

4. **Coverage limits.** The excerpts omit most of `wsgi_app` request dispatch, request-context setup/teardown, error handling, response coercion, static-file serving, configuration loaders, CLI command discovery, wrappers, and signal definitions. Thus the high-level dispatch and response return are established by Flask’s documented WSGI role and visible callable/routing state, but exact middleware, exception, session-open/save, and teardown ordering cannot be established from the sampled lines.

Main entry points: [`src/flask/app.py`](https://github.com/pallets/flask/blob/main/src/flask/app.py) (Flask WSGI Application), [`src/flask/templating.py`](https://github.com/pallets/flask/blob/main/src/flask/templating.py) (Template Rendering), [`src/flask/sansio/app.py`](https://github.com/pallets/flask/blob/main/src/flask/sansio/app.py) (Sans-IO Application Definition and Routing State), [`src/flask/sessions.py`](https://github.com/pallets/flask/blob/main/src/flask/sessions.py) (Secure Cookie Session Interface)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_external["External Boundary"]
  node_http_client(("HTTP Client<br/>external actor"))
  node_wsgi_server["WSGI Server<br/>external server"]
  node_user_app["User Application and View Callbacks<br/>external code"]
  node_werkzeug["Werkzeug<br/>external dependency"]
  node_jinja2["Jinja2<br/>external dependency"]
  node_itsdangerous["itsdangerous<br/>external dependency"]
end

subgraph group_core["Framework Core"]
  node_public_api["Public API Facade<br/>[__init__.py]"]
  node_flask_app["Flask WSGI Application<br/>[app.py]"]
  node_sansio_app["Sans-IO Application Definition and Routing State<br/>application state"]
  node_scaffold["Route and Error Registration Scaffold<br/>registration API"]
  node_blueprints["Blueprint Registration<br/>registration subsystem"]
end

subgraph group_request["Request and Rendering"]
  node_wrappers["Request and Response Wrappers<br/>HTTP wrappers"]
  node_contexts["Application and Request Contexts<br/>context state"]
  node_templating["Template Rendering<br/>rendering subsystem"]
  node_signals["Rendering Signals<br/>extension hooks"]
  node_json_api["JSON Convenience API<br/>JSON API"]
  node_json_provider["Application JSON Provider<br/>serialization provider"]
end

subgraph group_state_cli["State and CLI"]
  node_module_cli["Module CLI Entry Point<br/>[__main__.py]"]
  node_cli_runtime["CLI Command Runtime<br/>CLI runtime"]
  node_sessions["Secure Cookie Session Interface<br/>session subsystem"]
  node_session_tags["Tagged Session Serialization<br/>serialization subsystem"]
end

node_http_client -->|"sends request"| node_wsgi_server
node_wsgi_server -->|"invokes callable"| node_flask_app
node_user_app -->|"imports APIs"| node_public_api
node_public_api -->|"exposes Flask"| node_flask_app
node_flask_app -->|"initializes and uses"| node_sansio_app
node_sansio_app -->|"maintains URL rules"| node_werkzeug
node_user_app -->|"registers callbacks"| node_scaffold
node_scaffold -->|"forwards registration"| node_sansio_app
node_user_app -->|"defines blueprints"| node_blueprints
node_blueprints -->|"applies registrations"| node_sansio_app
node_flask_app -->|"dispatches endpoint"| node_user_app
node_user_app -->|"renders template"| node_templating
node_templating -->|"reads active context"| node_contexts
node_templating -->|"renders templates"| node_jinja2
node_templating -->|"emits render signals"| node_signals
node_user_app -->|"uses JSON helpers"| node_json_api
node_json_api -->|"delegates JSON operations"| node_json_provider
node_json_provider -->|"creates response"| node_flask_app
node_sessions -->|"serializes session"| node_session_tags
node_sessions -->|"protects cookies"| node_itsdangerous
node_user_app -->|"invokes module"| node_module_cli
node_module_cli -->|"calls CLI"| node_cli_runtime
node_flask_app -->|"creates command group"| node_cli_runtime
node_user_app -->|"returns handler result"| node_flask_app
node_flask_app -->|"returns WSGI response"| node_wsgi_server

click node_public_api "https://github.com/pallets/flask/blob/main/src/flask/__init__.py"
click node_flask_app "https://github.com/pallets/flask/blob/main/src/flask/app.py"
click node_sansio_app "https://github.com/pallets/flask/blob/main/src/flask/sansio/app.py"
click node_scaffold "https://github.com/pallets/flask/blob/main/src/flask/sansio/scaffold.py"
click node_blueprints "https://github.com/pallets/flask/blob/main/src/flask/sansio/blueprints.py"
click node_module_cli "https://github.com/pallets/flask/blob/main/src/flask/__main__.py"
click node_cli_runtime "https://github.com/pallets/flask/blob/main/src/flask/cli.py"
click node_wrappers "https://github.com/pallets/flask/blob/main/src/flask/wrappers.py"
click node_contexts "https://github.com/pallets/flask/blob/main/src/flask/ctx.py"
click node_templating "https://github.com/pallets/flask/blob/main/src/flask/templating.py"
click node_signals "https://github.com/pallets/flask/blob/main/src/flask/signals.py"
click node_json_api "https://github.com/pallets/flask/blob/main/src/flask/json/__init__.py"
click node_json_provider "https://github.com/pallets/flask/blob/main/src/flask/json/provider.py"
click node_sessions "https://github.com/pallets/flask/blob/main/src/flask/sessions.py"
click node_session_tags "https://github.com/pallets/flask/blob/main/src/flask/json/tag.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_http_client,node_wsgi_server,node_user_app,node_werkzeug,node_jinja2,node_itsdangerous toneBlue
class node_public_api,node_flask_app,node_sansio_app,node_scaffold,node_blueprints toneAmber
class node_wrappers,node_contexts,node_templating,node_signals,node_json_api,node_json_provider toneMint
class node_module_cli,node_cli_runtime,node_sessions,node_session_tags toneRose
```

## Components

### External Boundary

Clients, deployment, authors, and dependencies

- **HTTP Client**: external actor · Initiates HTTP requests
- **WSGI Server**: external server · Hosts and invokes the application
- **User Application and View Callbacks**: external code · Supplies application, routes, callbacks, and configuration
- **Werkzeug**: external dependency · Provides WSGI, HTTP, routing, exception, and response primitives
- **Jinja2**: external dependency · Renders templates
- **itsdangerous**: external dependency · Protects secure-cookie sessions

### Framework Core

Application construction, routing, and registration

- [Public API Facade](https://github.com/pallets/flask/blob/main/src/flask/__init__.py): API facade · Primary developer-facing import surface · `src/flask/__init__.py`
- [Flask WSGI Application](https://github.com/pallets/flask/blob/main/src/flask/app.py): WSGI application · Concrete Flask application and WSGI callable · `src/flask/app.py`
- [Sans-IO Application Definition and Routing State](https://github.com/pallets/flask/blob/main/src/flask/sansio/app.py): application state · Owns configuration, URL map, endpoints, and blueprint support · `src/flask/sansio/app.py`
- [Route and Error Registration Scaffold](https://github.com/pallets/flask/blob/main/src/flask/sansio/scaffold.py): registration API · Registers view functions and error handlers · `src/flask/sansio/scaffold.py`
- [Blueprint Registration](https://github.com/pallets/flask/blob/main/src/flask/sansio/blueprints.py): registration subsystem · Applies deferred application and resource registrations · `src/flask/sansio/blueprints.py`

### Request and Rendering

Contexts, responses, templates, JSON, and signals

- [Request and Response Wrappers](https://github.com/pallets/flask/blob/main/src/flask/wrappers.py): HTTP wrappers · Flask-specific request and response types · `src/flask/wrappers.py`
- [Application and Request Contexts](https://github.com/pallets/flask/blob/main/src/flask/ctx.py): context state · Context-local application and request state · `src/flask/ctx.py`
- [Template Rendering](https://github.com/pallets/flask/blob/main/src/flask/templating.py): rendering subsystem · Builds environments, loaders, and template responses · `src/flask/templating.py`
- [Rendering Signals](https://github.com/pallets/flask/blob/main/src/flask/signals.py): extension hooks · Emits template rendering lifecycle signals · `src/flask/signals.py`
- [JSON Convenience API](https://github.com/pallets/flask/blob/main/src/flask/json/__init__.py): JSON API · Exposes JSON load, dump, and jsonify helpers · `src/flask/json/__init__.py`
- [Application JSON Provider](https://github.com/pallets/flask/blob/main/src/flask/json/provider.py): serialization provider · Provides replaceable JSON behavior and responses · `src/flask/json/provider.py`

### State and CLI

Sessions and command runtime

- [Module CLI Entry Point](https://github.com/pallets/flask/blob/main/src/flask/__main__.py): CLI entry point · Invokes the framework CLI module · `src/flask/__main__.py`
- [CLI Command Runtime](https://github.com/pallets/flask/blob/main/src/flask/cli.py): CLI runtime · Provides framework and application command execution · `src/flask/cli.py`
- [Secure Cookie Session Interface](https://github.com/pallets/flask/blob/main/src/flask/sessions.py): session subsystem · Implements signed secure-cookie session behavior · `src/flask/sessions.py`
- [Tagged Session Serialization](https://github.com/pallets/flask/blob/main/src/flask/json/tag.py): serialization subsystem · Encodes non-standard session values as tagged JSON · `src/flask/json/tag.py`

## Connections

- HTTP Client → WSGI Server: sends request · External deployment boundary
- WSGI Server → Flask WSGI Application: invokes callable · Uses the WSGI environ and start_response interface
- User Application and View Callbacks → Public API Facade: imports APIs
- Public API Facade → Flask WSGI Application: exposes Flask
- Flask WSGI Application → Sans-IO Application Definition and Routing State: initializes and uses · Concrete application calls the inherited constructor
- Sans-IO Application Definition and Routing State → Werkzeug: maintains URL rules · Creates Werkzeug Rule objects and adds them to the URL map
- User Application and View Callbacks → Route and Error Registration Scaffold: registers callbacks · Uses route and error-handler decorators
- Route and Error Registration Scaffold → Sans-IO Application Definition and Routing State: forwards registration · Route registration invokes add_url_rule
- User Application and View Callbacks → Blueprint Registration: defines blueprints · Defines reusable route and resource groups
- Blueprint Registration → Sans-IO Application Definition and Routing State: applies registrations · Applies deferred rules to the application
- Flask WSGI Application → User Application and View Callbacks: dispatches endpoint · Dispatches the matched endpoint to its view callback
- User Application and View Callbacks → Template Rendering: renders template · May return an HTML or template response
- Template Rendering → Application and Request Contexts: reads active context · Injects g and request when available
- Template Rendering → Jinja2: renders templates · Uses the configured environment and loader
- Template Rendering → Rendering Signals: emits render signals · Emits before_render_template and template_rendered
- User Application and View Callbacks → JSON Convenience API: uses JSON helpers · May serialize response data with jsonify or JSON helpers
- JSON Convenience API → Application JSON Provider: delegates JSON operations · Uses current_app.json in application context
- Application JSON Provider → Flask WSGI Application: creates response · Produces the configured application response class
- Secure Cookie Session Interface → Tagged Session Serialization: serializes session · Uses tagged JSON serialization
- Secure Cookie Session Interface → itsdangerous: protects cookies · Uses URLSafeTimedSerializer and signature-error handling
- User Application and View Callbacks → Module CLI Entry Point: invokes module · May use python -m flask
- Module CLI Entry Point → CLI Command Runtime: calls CLI · Calls cli.main()
- Flask WSGI Application → CLI Command Runtime: creates command group · Creates an AppGroup for application-specific commands
- User Application and View Callbacks → Flask WSGI Application: returns handler result · Returns a result into Flask's request lifecycle
- Flask WSGI Application → WSGI Server: returns WSGI response · Completes the response after request processing
