flask
Generated 2026-10-03 14:06:15
Documentation
Diagrams
Overview
Main Purpose and Functionality
This is Flask, a WSGI web application framework. A Flask object (flask.app) is the central object of an application. It is created with the application's import name and acts as the registry for view functions, URL rules, template configuration and more. A WSGI server calls the app directly, and Flask.__call__() delegates to Flask.wsgi_app().
The flask package re-exports its public API from the modules that define it:
| Module | Exported names |
|---|---|
flask.app |
Flask |
flask.blueprints |
Blueprint |
flask.config |
Config |
flask.ctx |
after_this_request, copy_current_request_context, has_app_context, has_request_context |
flask.helpers |
abort, flash, get_flashed_messages, get_template_attribute, make_response, redirect, send_file, send_from_directory, stream_with_context, url_for |
flask.json |
jsonify |
flask.templating |
render_template, render_template_string, stream_template, stream_template_string |
flask.wrappers |
Request, Response |
The package also includes a flask.cli command-line interface for running a development server, opening a shell and listing routes.
Key Components and Responsibilities
Application classes
Scaffold(flask.sansio.scaffold) holds behavior shared byFlaskandBlueprint. It provides:- the route decorators
route(),get(),post(),put(),delete(),patch()andquery(), plusadd_url_rule()andendpoint(); - the hook registrars
before_request(),after_request(),teardown_request(),context_processor()andurl_value_preprocessor(); - the
static_folderandstatic_url_pathproperties andjinja_loader.
- the route decorators
App(Scaffold)(flask.sansio.app) is the I/O-independent application base. It handles:- construction parameters:
import_name, static and template folders,instance_path,host_matching,subdomain_matchingandroot_path; - the
name,logger,jinja_envanddebugproperties; make_config(),make_aborter(),auto_find_instance_path(),create_global_jinja_loader()andselect_jinja_autoescape();register_blueprint(),iter_blueprints()andadd_url_rule();- template registration decorators such as
template_filter().
- construction parameters:
Flask(App)(flask.app) adds the runtime parts:wsgi_app()and__call__();run(),send_static_file(),get_send_file_max_age(),open_resource()andopen_instance_resource();create_jinja_environment(),create_url_adapter(),raise_routing_exception(),update_template_context()andmake_shell_context().
Blueprint(Scaffold)(flask.sansio.blueprints) is a collection of routes and app-related functions that is registered on an application later. It provides:record()andrecord_once()for deferred setup functions;make_setup_state(),register()andregister_blueprint()for nested blueprints;app_template_filter(),add_app_template_filter()andapp_template_test()for app-wide template registrations.
Blueprint(SansioBlueprint)(flask.blueprints) addsget_send_file_max_age(),send_static_file()andopen_resource().
Configuration
Config(dict) (flask.config) behaves like a dict and can be filled from several sources:
from_envvar()from_prefixed_env()(prefix defaults to"FLASK", values parsed withjson.loadsby default)from_pyfile()from_object()from_file()(takes a caller-suppliedloadcallable)from_mapping()
get_namespace() extracts the keys under a given prefix.
Request, response and context
Request(flask.wrappers) is the default request object. It records the matched endpoint and view arguments, and exposesendpoint,blueprint,blueprints,max_content_length,max_form_memory_sizeandmax_form_parts. It also provideson_json_loading_failed().Response(flask.wrappers) works like Werkzeug's response but defaults to an HTML mimetype. It exposesmax_cookie_size.Flask.make_response()normally creates it.AppContext(flask.ctx) carries information about the app and, when handling a request, about the request. It is pushed at the start of each request or CLI command and popped at the end. It haspush(),pop(exc),from_environ(),has_request,copy(),request,sessionandmatch_request().
JSON
JSONProvider (flask.json.provider) is constructed with the app and defines dumps(), dump(), loads(), load() and response(). Subclasses can customize JSON behavior or use a different JSON library.
Debug helpers
flask.debughelpers.explain_template_loading_attempts() builds a report of each template loader tried. For each loader it lists the source (application or blueprint), the loader's public attributes via _dump_loader_info(), and whether the template was matched. It also looks up the current request's blueprint through the app context.
CLI
flask.cli is built on click:
- The group's
make_context()setsFLASK_RUN_FROM_CLI=truesoapp.run()becomes a no-op. It also attaches aScriptInfoasobj, built from the group'screate_app,set_debug_flagandload_dotenvsettings. - The group's
parse_args()handles theno_args_is_helpand help-option cases by callinghandle_parse_result()on the--env-fileand--appoptions early, so commands fromapp.clican be listed. - When listing commands, the group merges in the loaded app's
clicommands. ANoAppExceptionshows only its message, and any other exception shows the full traceback. run_command(run) accepts--host,--port,--cert,--key,--reload/--no-reload,--debugger/--no-debugger,--with-threads/--without-threads,--extra-filesand--exclude-patterns.- The
shellcommand opens an interactive interpreter with a banner showing the Python version, app and instance path. It runs anyPYTHONSTARTUPscript, loadscurrent_app.make_shell_context()into the namespace and installs areadlinecompleter bound to that namespace. routes_command(routes) listscurrent_app.url_maprules.--sortacceptsendpoint,methods,domain,ruleormatch, wherematchis the order Flask matches routes when dispatching.--all-methodsincludes HEAD and OPTIONS.mainis the CLI entry point.
How Different Parts Work Together
Request handling
Flask.wsgi_app() is the core of request processing:
- It creates a context with
self.request_context(environ), then callsctx.push()andself.full_dispatch_request(ctx). - If an
Exceptionis raised, it records the error and produces the response throughself.handle_exception(ctx, e). Non-Exceptionexceptions are recorded and re-raised. - It calls the response as a WSGI application with
(environ, start_response). - In the
finallyblock it hands the context toenviron["werkzeug.debug.preserve_context"]if that key is present. Ifshould_ignore_erroris set and returns true for the error, the error is cleared. It then callsctx.pop(error).
__call__() is kept separate from wsgi_app() so middleware can wrap app.wsgi_app without losing the reference to the app object:
app.wsgi_app = MyMiddleware(app.wsgi_app)
Registration and blueprints
Both Flask and Blueprint get their decorators (route(), before_request() and so on) from Scaffold, so they are used the same way. A blueprint does not act immediately. Its Blueprint.register(app, options) is called when it is registered on an app, and record() and record_once() store deferred setup functions. Blueprint.make_setup_state() creates the state those functions run against. Blueprints can also register other blueprints through register_blueprint().
Configuration and CLI flow
The app builds its config in App.make_config(), and Config loads values from files, objects, mappings or environment variables. The CLI group loads the app through ScriptInfo, and commands such as shell and routes use current_app inside an app context. shell also relies on Flask.make_shell_context().
Overall Architecture and Design Patterns
- Library/framework style: Flask is a micro-framework built around one central application object plus context objects, not a service.
- Sans-I/O layering: I/O-independent logic lives in
flask.sansio(Scaffold,App,Blueprint). The concreteFlaskandBlueprintclasses inflask.appandflask.blueprintssubclass those and add file access, static file serving and the WSGI interface. Withinflask.sansio,Scaffoldis the common base for bothAppandBlueprint. - Template Method / extension points:
Apphas overridable factory-style methods, such asmake_config(),make_aborter(),create_jinja_environment(),create_url_adapter()andmake_setup_state(). These let subclasses customize the objects the app builds. - Strategy:
JSONProviderdefines a pluggable JSON interface bound to an app, so serialization can be swapped without changing callers likejsonify. - Decorator-based registration: routes, request hooks, context processors and template filters are all registered with decorators, with
add_url_rule()as the underlying call. - Command pattern with deferred execution: blueprints record setup functions and replay them at registration time.
- Context objects:
AppContextis pushed and popped around each request and CLI command, which is how helpers likecurrent_appwork.wsgi_app()guarantees the pop, passing along any error, even when handling fails. - Decorator/wrapper pattern:
RequestandResponseextend Werkzeug's classes with Flask-specific behavior, and the WSGI middleware pattern is supported directly through the__call__()/wsgi_app()split.