Key Classes and Functions

Core Classes

Scaffold (flask.sansio.scaffold)

Scaffold holds the behavior shared by Flask and Blueprint. Putting it in one base class lets applications and blueprints expose the same registration API.

  • Constructor: Scaffold(import_name, static_folder=None, static_url_path=None, template_folder=None, root_path=None).
  • Static files and templates: static_folder and static_url_path are properties with setters. has_static_folder and jinja_loader are also available.
  • Route registration: route(), add_url_rule(), and the HTTP-method shortcuts get(), query(), post(), put(), delete(), and patch(). Each takes rule plus **options. endpoint() registers a function for a named endpoint.
  • Hook decorators: before_request(), after_request(), teardown_request(), context_processor(), and url_value_preprocessor().
  • Hook storage: before_request_funcs, after_request_funcs, and teardown_request_funcs are defaultdict(list) objects keyed by scope. The scope is a blueprint name, or None for functions that apply to all requests. These dictionaries are internal, should not be modified directly, and their format may change. Use the decorators instead.
    • teardown_request functions run at the end of each request even if an exception is raised.

App (flask.sansio.app)

App(Scaffold) is the central registry for view functions, URL rules, and template configuration. Its first parameter, import_name, tells Flask what belongs to the application. It is used to find resources on the filesystem and can be used by extensions to improve debugging information.

  • Constructor: App(import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None).
  • Properties: name, logger, jinja_env, and debug (with a setter).
  • Factory methods: make_config(), make_aborter(), create_jinja_environment(), create_global_jinja_loader(), auto_find_instance_path(), and select_jinja_autoescape().
  • Registration: register_blueprint(), iter_blueprints(), add_url_rule(), and template_filter().

For a single module, pass __name__. For a package, the recommended value is the hardcoded package name, or __name__.split('.')[0].

Flask (flask.app)

Flask(App) is the concrete WSGI application. It takes the same constructor parameters as App.

  • Resources and static files: open_resource() (default mode 'rb'), open_instance_resource() (default encoding 'utf-8'), send_static_file(), and get_send_file_max_age().
  • Routing and templating: create_jinja_environment(), create_url_adapter(), raise_routing_exception(), and update_template_context().
  • Shell and server: make_shell_context() and run(host=None, port=None, debug=None, load_dotenv=True, **options).

Blueprint

A blueprint is a collection of routes and other app-related functions that can be registered on a real application later. It comes in two layers.

  • flask.sansio.blueprints.Blueprint(Scaffold):
    • The constructor is Blueprint(name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None, cli_group=_sentinel).
    • record() and record_once() take a DeferredSetupFunction.
    • make_setup_state(), register(), register_blueprint(), and add_url_rule() complete the registration side.
    • App-wide registration is available through app_template_filter(), add_app_template_filter(), and app_template_test().
  • flask.blueprints.Blueprint(SansioBlueprint): adds get_send_file_max_age(), send_static_file(), and open_resource() (default encoding 'utf-8').

Config (flask.config)

Config(dict) works like a dict but can be filled from files or special dictionaries. The constructor is Config(root_path, defaults=None).

Method Purpose (from signature)
from_envvar(variable_name, silent=False) Load using an environment variable name
from_prefixed_env(prefix='FLASK', *, loads=json.loads) Load prefixed environment variables, with a configurable loads callable
from_pyfile(filename, silent=False) Load from a Python file
from_object(obj) Load from an object or a string
from_file(filename, load, silent=False, text=True) Load a file using a caller-supplied load callable
from_mapping(mapping=None, **kwargs) Load from a mapping or keyword arguments
get_namespace(namespace, lowercase=True, trim_namespace=True) Extract a namespaced subset

Request and Response (flask.wrappers)

  • Request(RequestBase): the default request object. It remembers the matched endpoint and view arguments. It provides:
    • properties endpoint, blueprint, and blueprints
    • max_content_length, max_form_memory_size, and max_form_parts, each with a setter
    • on_json_loading_failed()
  • Response(ResponseBase): works like Werkzeug's response but has an HTML mimetype by default. It adds max_cookie_size. Usually you don't create it yourself because Flask.make_response() does. To replace it, subclass it and set Flask.response_class.

AppContext (flask.ctx)

An AppContext holds information about an app, and about the request when handling one. A context is pushed at the beginning of each request and CLI command, and popped at the end. It is called a "request context" if it has request information, and an "app context" if not.

  • Constructor: AppContext(app, *, request=None, session=None).
  • Factory and lifecycle: the classmethod from_environ(app, environ), push(), pop(exc=None), and copy().
  • Request state: has_request, request, session, and match_request().

SessionInterface (flask.sessions)

This is the interface to implement to replace the default session interface, which uses werkzeug's securecookie implementation. Only open_session(app, request) and save_session(app, session, response) must be implemented. The other methods have useful defaults:

  • make_null_session() and is_null_session()
  • get_cookie_name(), get_cookie_domain(), get_cookie_path(), get_cookie_httponly(), get_cookie_secure(), get_cookie_samesite(), and get_cookie_partitioned()
  • get_expiration_time() and should_set_cookie()

JSONProvider (flask.json.provider)

JSONProvider(app) is a standard set of JSON operations for an application. Subclasses can customize JSON behavior or use different JSON libraries. Its methods are dumps(), dump(), loads(), load(), and response().

MethodView (flask.views)

MethodView(View) dispatches request methods to the corresponding instance methods. A get method handles GET requests, which is useful for REST APIs. methods is set automatically from the methods defined on the class, via __init_subclass__. dispatch_request() performs the dispatch.

Environment (flask.templating)

Environment(BaseEnvironment) works like a regular Jinja environment but knows how Flask blueprints work. It can prepend the blueprint name to referenced templates when necessary.

TagMarkup (flask.json.tag)

TagMarkup(JSONTag) serializes anything matching the markupsafe.Markup API (anything with an __html__ method) to the result of that method. It always deserializes to a Markup instance. It implements check(), to_json(), and to_python().

Helper Functions

The top-level flask package re-exports the public helpers and proxies, grouped here by source module.

Source module Names
flask.ctx after_this_request, copy_current_request_context, has_app_context, has_request_context
flask.globals current_app, g, request, session
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 (the json module is also exported)
flask.templating render_template, render_template_string, stream_template, stream_template_string
flask.signals appcontext_popped, appcontext_pushed, appcontext_tearing_down, before_render_template, got_request_exception, message_flashed, request_finished, request_started, request_tearing_down, template_rendered

The classes Flask, Blueprint, and Config are re-exported from the same package root.

Class Relationships

Scaffold                      (flask.sansio.scaffold)
├── App                       (flask.sansio.app)
│   └── Flask                 (flask.app)
└── Blueprint                 (flask.sansio.blueprints)
    └── Blueprint             (flask.blueprints, subclass of the sansio one)

dict ── Config                (flask.config)
RequestBase ── Request        (flask.wrappers)
ResponseBase ── Response      (flask.wrappers)
View ── MethodView            (flask.views)
BaseEnvironment ── Environment (flask.templating)
JSONTag ── TagMarkup          (flask.json.tag)
  • Layering: the sansio package holds the base App and Blueprint classes. The classes in flask.app and flask.blueprints add the file and resource methods: open_resource(), send_static_file(), and get_send_file_max_age().
  • Shared API: Flask and Blueprint both inherit from Scaffold, so route(), before_request(), and the other decorators work on both.
  • Composition:
    • JSONProvider is constructed with an App.
    • AppContext is constructed with a Flask app and optionally a Request and a session.
    • SessionInterface methods take the Flask app as an argument.
  • Extension points: subclass SessionInterface (implement open_session() and save_session()), JSONProvider, or Response (assigned to Flask.response_class).

Usage Examples

Creating an application

from flask import Flask

app = Flask(__name__)

For a package, use a hardcoded name:

app = Flask('yourapplication')
# or
app = Flask(__name__.split('.')[0])

Registering a route

@app.route("/")
def index():
    ...

Class-based views with MethodView

from flask import session, redirect, url_for
from flask.views import MethodView

class CounterAPI(MethodView):
    def get(self):
        return str(session.get("counter", 0))

    def post(self):
        session["counter"] = session.get("counter", 0) + 1
        return redirect(url_for("counter"))

app.add_url_rule(
    "/counter", view_func=CounterAPI.as_view("counter")
)

Blueprints

from flask import Blueprint

bp = Blueprint("example", __name__, url_prefix="/example")

app.register_blueprint(bp)

Populating configuration

app.config.from_mapping(SECRET_KEY="dev")
app.config.from_prefixed_env()   # prefix defaults to 'FLASK'

Running the development server

app.run(host="127.0.0.1", port=5000, debug=True)