Bases: matplotlib.widgets.SliderBase
A slider representing a floating point range.
Create a slider from valmin to valmax in axes ax. For the slider to remain responsive you must maintain a reference to it. Call on_changed() to connect to the slider event.
Slider value.
The Axes to put the slider in.
Slider label.
The minimum value of the slider.
The maximum value of the slider.
The slider initial position.
%-format string used to format the slider value. If None, a ScalarFormatter is used instead.
Whether the slider interval is closed on the bottom.
Whether the slider interval is closed on the top.
Do not allow the current slider to have a value less than the value of the Slider slidermin.
Do not allow the current slider to have a value greater than the value of the Slider slidermax.
If True the slider can be dragged by the mouse.
If a float, the slider will snap to multiples of valstep. If an array the slider will snap to the values in the array.
The orientation of the slider.
The color of the line at the valinit position. Set to 'none' for no line.
The color of the background track. The track is accessible for further styling via the track attribute.
Properties of the slider handle. Default values are
Key
Value
Default
Description
facecolor
color
'white'
The facecolor of the slider handle.
edgecolor
color
'.75'
The edgecolor of the slider handle.
size
int
10
The size of the slider handle in points.
Other values will be transformed as marker{foo} and passed to the Line2D constructor. e.g. handle_style = {'style'='x'} will result in markerstyle = 'x'.
Additional kwargs are passed on to self.poly which is the Polygon that draws the slider knob. See the Polygon documentation for valid property names (facecolor, edgecolor, alpha, etc.).
Connect func as callback function to changes of the slider value.
Function to call when slider is changed. The function must accept a single float as its arguments.
Connection id (which can be used to disconnect func).
Set slider value to val.


Connect func as callback function to changes of the slider value.
Function to call when slider is changed. The function must accept a single float as its arguments.
Connection id (which can be used to disconnect func).


Bases: matplotlib.widgets.AxesWidget
The base class for constructing Slider widgets. Not intended for direct usage.
For the slider to remain responsive you must maintain a reference to it.
Remove the observer with connection id cid.
Connection id of the observer to be removed.
Reset the slider to the initial value.


Remove the observer with connection id cid.
Connection id of the observer to be removed.


Bases: matplotlib.widgets._SelectorWidget
Visually select a min/max range on a single axis and call a function with those values.
To guarantee that the selector remains responsive, keep a reference to it.
In order to turn off the SpanSelector, set span_selector.active to False. To turn it back on, set it to True.
Press and release events triggered at the same coordinates outside the selection will clear the selector, except when ignore_event_outside=True.
A callback function that is called after a release event and the selection is created, changed or removed. It must have the signature:
The direction along which to draw the span selector.
If selection is less than or equal to minspan, the selection is removed (when already existing) or cancelled.
If True, use the backend-dependent blitting features for faster canvas updates.
Dictionary of matplotlib.patches.Patch properties. Default:
dict(facecolor='red', alpha=0.5)
Called on mouse move while the span is being selected.
If True, the span stays visible after the mouse is released. Deprecated, use interactive instead.
Whether to draw a set of handles that allow interaction with the widget after it is drawn.
The mouse buttons which activate the span selector.
Properties of the handle lines at the edges of the span. Only used when interactive is True. See matplotlib.lines.Line2D for valid properties.
Distance in pixels within which the interactive tool handles can be activated.
If True, the widget can be moved by clicking anywhere within its bounds.
If True, the event triggered outside the span selector will be ignored.
See also: Span Selector
Connect the major canvas events to methods.
Direction of the span selector: 'vertical' or 'horizontal'.
Return extents of the span selector.
Set SpanSelector to operate on a new Axes.


Connect the major canvas events to methods.


Set SpanSelector to operate on a new Axes.


Bases: matplotlib.widgets.Widget
A tool to adjust the subplot params of a matplotlib.figure.Figure.
The figure instance to adjust.
The figure instance to embed the subplot tool into.


Bases: matplotlib.widgets.AxesWidget
A GUI neutral text input box.
For the text box to remain responsive you must keep a reference to it.
Call on_text_change to be updated whenever the text changes.
Call on_submit to be updated whenever the user hits enter or leaves the text entry field.
The parent axes for the widget.
The color of the text box when not hovering.
The color of the text box when hovering.
The Axes instance the button will be placed into.
Label for this text box.
Initial value in the text box.
The color of the box.
The color of the box when the mouse is over it.
The distance between the label and the right side of the textbox.
The horizontal location of the text.
Remove the observer with connection id cid.
When the user hits enter or leaves the submission box, call this func with event.
A connection id is returned which can be used to disconnect.
When the text changes, call this func with event.
A connection id is returned which can be used to disconnect.


Remove the observer with connection id cid.


When the user hits enter or leaves the submission box, call this func with event.
A connection id is returned which can be used to disconnect.


When the text changes, call this func with event.
A connection id is returned which can be used to disconnect.


Bases: object
Control handles for canvas tools.
Matplotlib axes where tool handles are displayed.
Coordinates of control handles.
Shape of marker used to display handle. See matplotlib.pyplot.plot.
Additional marker properties. See matplotlib.lines.Line2D.
Whether to use blitting for faster drawing (if supported by the backend).
Return index and pixel distance to closest index.
Set x and y positions of handles.


Return index and pixel distance to closest index.


Bases: object
Control handles for canvas tools.
Matplotlib axes where tool handles are displayed.
Positions of handles in data coordinates.
Direction of handles, either 'vertical' or 'horizontal'
Additional line properties. See matplotlib.lines.Line2D.
Whether to use blitting for faster drawing (if supported by the backend).
Return index and pixel distance to closest handle.
x, y position from which the distance will be calculated to determinate the closest handle
position x, y
Direction of the handle: 'vertical' or 'horizontal'.
Positions of the handle in data coordinates.
Remove the handles artist from the figure.
Set the animated state of the handles artist.
Set x or y positions of handles, depending if the lines are vertical of horizontal.
Set the positions of the handle in data coordinates
Set the visibility state of the handles artist.


Return index and pixel distance to closest handle.
x, y position from which the distance will be calculated to determinate the closest handle
position x, y


Remove the handles artist from the figure.


Set the animated state of the handles artist.


Set x or y positions of handles, depending if the lines are vertical of horizontal.
Set the positions of the handle in data coordinates


Set the visibility state of the handles artist.


Bases: object
Abstract base class for GUI neutral widgets.
Is the widget active?
Get whether the widget is active.
Return whether event should be ignored.
This method should be called at the beginning of any event callback.
Set whether the widget is active.


Return whether event should be ignored.
This method should be called at the beginning of any event callback.


Raises an HTTPException for the given status code or WSGI application.
If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that:
NoReturn


Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one.
Example:
This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object.
New in version 0.9.
f (Callable[[Response], Response]) –
Callable[[Response], Response]


The application context binds an application object implicitly to the current thread or greenlet, similar to how the RequestContext binds request information. The application context is also implicitly created if a request context is created but the application is not on top of the individual application context.
app (Flask) –
None
Pops the app context.
exc (Optional[BaseException]) –
None
Binds the app context to the current context.
None


Pops the app context.
exc (Optional[BaseException]) –
None


Binds the app context to the current context.
None


This works similar to a regular click Group but it changes the behavior of the command() decorator so that it automatically wraps the functions in with_appcontext().
Not to be confused with FlaskGroup.
None
This works exactly like the method of the same name on a regular click.Group but it wraps callbacks in with_appcontext() unless it’s disabled by passing with_appcontext=False.
This works exactly like the method of the same name on a regular click.Group but it defaults the group class to AppGroup.


This works exactly like the method of the same name on a regular click.Group but it wraps callbacks in with_appcontext() unless it’s disabled by passing with_appcontext=False.


This works exactly like the method of the same name on a regular click.Group but it defaults the group class to AppGroup.


Inform the application what path it is mounted under by the application / web server. This is used for generating URLs outside the context of a request (inside a request, the dispatcher is responsible for setting SCRIPT_NAME instead; see Application Dispatching for examples of dispatch configuration).
Will be used for the session cookie path if SESSION_COOKIE_PATH is not set.
Default: '/'


If you’d like to use an ASGI server you will need to utilise WSGI to ASGI middleware. The asgiref [WsgiToAsgi](https://github.com/django/asgiref#wsgi-to-asgi-adapter) adapter is recommended as it integrates with the event loop used for Flask’s Using async and await support. You can use the adapter by wrapping the Flask app,
and then serving the asgi_app with the asgi server, e.g. using Hypercorn,


Represents a blueprint, a collection of routes and other app-related functions that can be registered on a real application later.
A blueprint is an object that allows defining application functions without requiring an application object ahead of time. It uses the same decorators as Flask, but defers the need for an application by recording them for later registration.
Decorating a function with a blueprint creates a deferred function that is called with BlueprintSetupState when the blueprint is registered on an application.
See Modular Applications with Blueprints for more information.
Changed in version 1.1.0: Blueprints have a cli group to register nested CLI commands. The cli_group parameter controls the name of the group under the flask command.
New in version 0.7.
Register a custom template filter, available application wide. Like Flask.add_template_filter() but for a blueprint. Works exactly like the app_template_filter() decorator.
None
Register a custom template global, available application wide. Like Flask.add_template_global() but for a blueprint. Works exactly like the app_template_global() decorator.
New in version 0.10.
None
Register a custom template test, available application wide. Like Flask.add_template_test() but for a blueprint. Works exactly like the app_template_test() decorator.
New in version 0.10.
None
Like Flask.add_url_rule() but for a blueprint. The endpoint for the url_for() function is prefixed with the name of the blueprint.
None
Like Flask.after_request() but for a blueprint. Such a function is executed after each request, even if outside of the blueprint.
f (Callable[[Response], Response]) –
Callable[[Response], Response]
Register a function to run after each request to this object.
The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent.
If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request() for that.
f (Callable[[Response], Response]) –
Callable[[Response], Response]
A data structure of functions to call at the end of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the after_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
Like Flask.context_processor() but for a blueprint. Such a function is executed each request, even if outside of the blueprint.
f (Callable[[], Dict[str, Any]]) –
Callable[[], Dict[str, Any]]
Like Flask.errorhandler() but for a blueprint. This handler is used for all requests, even if outside of the blueprint.
code (Union[Type[Exception], int]) –
Callable
Register a custom template filter, available application wide. Like Flask.template_filter() but for a blueprint.
name (Optional[str]) – the optional name of the filter, otherwise the function name will be used.
Callable
Register a custom template global, available application wide. Like Flask.template_global() but for a blueprint.
New in version 0.10.
name (Optional[str]) – the optional name of the global, otherwise the function name will be used.
Callable
Register a custom template test, available application wide. Like Flask.template_test() but for a blueprint.
New in version 0.10.
name (Optional[str]) – the optional name of the test, otherwise the function name will be used.
Callable
Same as url_defaults() but application wide.
f (Callable[[str, dict], None]) –
Callable[[str, dict], None]
Same as url_value_preprocessor() but application wide.
f (Callable[[Optional[str], Optional[dict]], None]) –
Callable[[Optional[str], Optional[dict]], None]
Like Flask.before_first_request(). Such a function is executed before the first request to the application.
f (Callable[[], None]) –
Callable[[], None]
Like Flask.before_request(). Such a function is executed before each request, even if outside of a blueprint.
f (Callable[[], None]) –
Callable[[], None]
Register a function to run before each request.
For example, this can be used to open a database connection, or to load the logged in user from the session.
The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped.
f (Callable[[], None]) –
Callable[[], None]
A data structure of functions to call at the beginning of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the before_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
The Click command group for registering CLI commands for this object. The commands are available from the flask command once the application has been discovered and blueprints have been registered.
Registers a template context processor function.
f (Callable[[], Dict[str, Any]]) –
Callable[[], Dict[str, Any]]
Shortcut for route() with methods=["DELETE"].
New in version 2.0.
Callable
Decorate a view function to register it for the given endpoint. Used if a rule is added without a view_func with add_url_rule().
endpoint (str) – The endpoint name to associate with the view function.
Callable
A data structure of registered error handlers, in the format {scope: {code: {class: handler}}}`. The scope key is the name of a blueprint the handlers are active for, or None for all requests. The code key is the HTTP status code for HTTPException, or None for other exceptions. The innermost dictionary maps exception classes to handler functions.
To register an error handler, use the errorhandler() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
Register a function to handle errors by code or exception class.
A decorator that is used to register a function given an error code. Example:
You can also register handlers for arbitrary exceptions:
New in version 0.7: Use register_error_handler() instead of modifying error_handler_spec directly, for application wide error handlers.
New in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the HTTPException class.
code_or_exception (Union[Type[Exception], int]) – the code as integer for the handler, or an arbitrary exception
Callable
Shortcut for route() with methods=["GET"].
New in version 2.0.
Callable
Used by send_file() to determine the max_age cache value for a given file path if it wasn’t passed.
By default, this returns SEND_FILE_MAX_AGE_DEFAULT from the configuration of current_app. This defaults to None, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable.
Changed in version 2.0: The default configuration is None instead of 12 hours.
New in version 0.9.
filename (str) –
Optional[int]
True if static_folder is set.
New in version 0.5.
The name of the package or module that this object belongs to. Do not change this once it is set by the constructor.
The Jinja loader for this object’s templates. By default this is a class jinja2.loaders.FileSystemLoader to template_folder if it is set.
New in version 0.5.
Blueprint local JSON decoder class to use. Set to None to use the app’s json_decoder.
Blueprint local JSON encoder class to use. Set to None to use the app’s json_encoder.
Creates an instance of BlueprintSetupState() object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state.
flask.blueprints.BlueprintSetupState
Open a resource file relative to root_path for reading.
For example, if the file schema.sql is next to the file app.py where the Flask app is defined, it can be opened with:
IO
Shortcut for route() with methods=["PATCH"].
New in version 2.0.
Callable
Shortcut for route() with methods=["POST"].
New in version 2.0.
Callable
Shortcut for route() with methods=["PUT"].
New in version 2.0.
Callable
Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the make_setup_state() method.
func (Callable) –
None
Works like record() but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called.
func (Callable) –
None
Called by Flask.register_blueprint() to register all views and callbacks registered on the blueprint with the application. Creates a BlueprintSetupState and calls each record() callbackwith it.
None
Register a Blueprint on this blueprint. Keyword arguments passed to this method will override the defaults set on the blueprint.
New in version 2.0.
None
Alternative error attach function to the errorhandler() decorator that is more straightforward to use for non decorator usage.
New in version 0.7.
None
Absolute path to the package on the filesystem. Used to look up resources contained in the package.
Decorate a view function to register it with the given URL rule and options. Calls add_url_rule(), which has more details about the implementation.
See URL Route Registrations.
The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn’t passed.
The methods parameter defaults to ["GET"]. HEAD and OPTIONS are added automatically.
Callable
The view function used to serve files from static_folder. A route is automatically registered for this view at static_url_path if static_folder is set.
New in version 0.5.
filename (str) –
Response
The absolute path to the configured static folder. None if no static folder is set.
The URL prefix that the static route will be accessible from.
If it was not configured during init, it is derived from static_folder.
Like Flask.teardown_request() but for a blueprint. Such a function is executed when tearing down each request, even if outside of the blueprint.
f (Callable[[Optional[BaseException]], Response]) –
Callable[[Optional[BaseException]], Response]
Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed.
Example:
When ctx.pop() is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests.
Teardown functions must avoid raising exceptions, since they . If they execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors.
When a teardown function was called because of an exception it will be passed an error object.
The return values of teardown functions are ignored.
Debug Note
In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable.
f (Callable[[Optional[BaseException]], Response]) –
Callable[[Optional[BaseException]], Response]
A data structure of functions to call at the end of each request even if an exception is raised, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the teardown_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
A data structure of functions to call to pass extra context values when rendering templates, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the context_processor() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
The path to the templates folder, relative to root_path, to add to the template loader. None if templates should not be added.
A data structure of functions to call to modify the keyword arguments when generating URLs, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the url_defaults() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place.
f (Callable[[str, dict], None]) –
Callable[[str, dict], None]
Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request() functions.
The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in g rather than pass it to every view.
The function is passed the endpoint name and values dict. The return value is ignored.
f (Callable[[Optional[str], Optional[dict]], None]) –
Callable[[Optional[str], Optional[dict]], None]
A data structure of functions to call to modify the keyword arguments passed to the view function, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the url_value_preprocessor() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
A dictionary mapping endpoint names to view functions.
To register a view function, use the route() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.


Register a custom template filter, available application wide. Like Flask.add_template_filter() but for a blueprint. Works exactly like the app_template_filter() decorator.
None


Register a custom template global, available application wide. Like Flask.add_template_global() but for a blueprint. Works exactly like the app_template_global() decorator.
New in version 0.10.
None


Register a custom template test, available application wide. Like Flask.add_template_test() but for a blueprint. Works exactly like the app_template_test() decorator.
New in version 0.10.
None


Like Flask.add_url_rule() but for a blueprint. The endpoint for the url_for() function is prefixed with the name of the blueprint.
None


Like Flask.after_request() but for a blueprint. Such a function is executed after each request, even if outside of the blueprint.
f (Callable[[Response], Response]) –
Callable[[Response], Response]


Register a function to run after each request to this object.
The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent.
If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request() for that.
f (Callable[[Response], Response]) –
Callable[[Response], Response]


A data structure of functions to call at the end of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the after_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.


Like Flask.context_processor() but for a blueprint. Such a function is executed each request, even if outside of the blueprint.
f (Callable[[], Dict[str, Any]]) –
Callable[[], Dict[str, Any]]


Like Flask.errorhandler() but for a blueprint. This handler is used for all requests, even if outside of the blueprint.
code (Union[Type[Exception], int]) –
Callable


Register a custom template filter, available application wide. Like Flask.template_filter() but for a blueprint.
name (Optional[str]) – the optional name of the filter, otherwise the function name will be used.
Callable


Register a custom template global, available application wide. Like Flask.template_global() but for a blueprint.
New in version 0.10.
name (Optional[str]) – the optional name of the global, otherwise the function name will be used.
Callable


Register a custom template test, available application wide. Like Flask.template_test() but for a blueprint.
New in version 0.10.
name (Optional[str]) – the optional name of the test, otherwise the function name will be used.
Callable


Same as url_defaults() but application wide.
f (Callable[[str, dict], None]) –
Callable[[str, dict], None]


Same as url_value_preprocessor() but application wide.
f (Callable[[Optional[str], Optional[dict]], None]) –
Callable[[Optional[str], Optional[dict]], None]


Like Flask.before_first_request(). Such a function is executed before the first request to the application.
f (Callable[[], None]) –
Callable[[], None]


Like Flask.before_request(). Such a function is executed before each request, even if outside of a blueprint.
f (Callable[[], None]) –
Callable[[], None]


Register a function to run before each request.
For example, this can be used to open a database connection, or to load the logged in user from the session.
The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped.
f (Callable[[], None]) –
Callable[[], None]


A data structure of functions to call at the beginning of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the before_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.


The Click command group for registering CLI commands for this object. The commands are available from the flask command once the application has been discovered and blueprints have been registered.


Registers a template context processor function.
f (Callable[[], Dict[str, Any]]) –
Callable[[], Dict[str, Any]]


Shortcut for route() with methods=["DELETE"].
New in version 2.0.
Callable


Decorate a view function to register it for the given endpoint. Used if a rule is added without a view_func with add_url_rule().
endpoint (str) – The endpoint name to associate with the view function.
Callable


Register a function to handle errors by code or exception class.
A decorator that is used to register a function given an error code. Example:
You can also register handlers for arbitrary exceptions:
New in version 0.7: Use register_error_handler() instead of modifying error_handler_spec directly, for application wide error handlers.
New in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the HTTPException class.
code_or_exception (Union[Type[Exception], int]) – the code as integer for the handler, or an arbitrary exception
Callable


A data structure of registered error handlers, in the format {scope: {code: {class: handler}}}`. The scope key is the name of a blueprint the handlers are active for, or None for all requests. The code key is the HTTP status code for HTTPException, or None for other exceptions. The innermost dictionary maps exception classes to handler functions.
To register an error handler, use the errorhandler() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.


Shortcut for route() with methods=["GET"].
New in version 2.0.
Callable


Used by send_file() to determine the max_age cache value for a given file path if it wasn’t passed.
By default, this returns SEND_FILE_MAX_AGE_DEFAULT from the configuration of current_app. This defaults to None, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable.
Changed in version 2.0: The default configuration is None instead of 12 hours.
New in version 0.9.
filename (str) –
Optional[int]


The name of the package or module that this object belongs to. Do not change this once it is set by the constructor.


Blueprint local JSON decoder class to use. Set to None to use the app’s json_decoder.


Blueprint local JSON encoder class to use. Set to None to use the app’s json_encoder.


Creates an instance of BlueprintSetupState() object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state.
flask.blueprints.BlueprintSetupState


Open a resource file relative to root_path for reading.
For example, if the file schema.sql is next to the file app.py where the Flask app is defined, it can be opened with:
IO


Shortcut for route() with methods=["PATCH"].
New in version 2.0.
Callable


Shortcut for route() with methods=["POST"].
New in version 2.0.
Callable


Shortcut for route() with methods=["PUT"].
New in version 2.0.
Callable


Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the make_setup_state() method.
func (Callable) –
None


Works like record() but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called.
func (Callable) –
None


Called by Flask.register_blueprint() to register all views and callbacks registered on the blueprint with the application. Creates a BlueprintSetupState and calls each record() callbackwith it.
None


Register a Blueprint on this blueprint. Keyword arguments passed to this method will override the defaults set on the blueprint.
New in version 2.0.
None


Alternative error attach function to the errorhandler() decorator that is more straightforward to use for non decorator usage.
New in version 0.7.
None


Absolute path to the package on the filesystem. Used to look up resources contained in the package.


Decorate a view function to register it with the given URL rule and options. Calls add_url_rule(), which has more details about the implementation.
See URL Route Registrations.
The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn’t passed.
The methods parameter defaults to ["GET"]. HEAD and OPTIONS are added automatically.
Callable


The view function used to serve files from static_folder. A route is automatically registered for this view at static_url_path if static_folder is set.
New in version 0.5.
filename (str) –
Response


Like Flask.teardown_request() but for a blueprint. Such a function is executed when tearing down each request, even if outside of the blueprint.
f (Callable[[Optional[BaseException]], Response]) –
Callable[[Optional[BaseException]], Response]


Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed.
Example:
When ctx.pop() is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests.
Teardown functions must avoid raising exceptions, since they . If they execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors.
When a teardown function was called because of an exception it will be passed an error object.
The return values of teardown functions are ignored.
Debug Note
In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable.
f (Callable[[Optional[BaseException]], Response]) –
Callable[[Optional[BaseException]], Response]


A data structure of functions to call at the end of each request even if an exception is raised, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the teardown_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.


A data structure of functions to call to pass extra context values when rendering templates, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the context_processor() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.


The path to the templates folder, relative to root_path, to add to the template loader. None if templates should not be added.


Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place.
f (Callable[[str, dict], None]) –
Callable[[str, dict], None]


A data structure of functions to call to modify the keyword arguments when generating URLs, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the url_defaults() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.


Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request() functions.
The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in g rather than pass it to every view.
The function is passed the endpoint name and values dict. The return value is ignored.
f (Callable[[Optional[str], Optional[dict]], None]) –
Callable[[Optional[str], Optional[dict]], None]


A data structure of functions to call to modify the keyword arguments passed to the view function, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the url_value_preprocessor() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.


A dictionary mapping endpoint names to view functions.
To register a view function, use the route() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.


Temporary holder object for registering a blueprint with the application. An instance of this class is created by the make_setup_state() method and later passed to all register callback functions.
None
A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint’s name.
None
a reference to the current application
a reference to the blueprint that created this setup state.
as blueprints can be registered multiple times with the application and not everything wants to be registered multiple times on it, this attribute can be used to figure out if the blueprint was registered in the past already.
a dictionary with all options that were passed to the register_blueprint() method.
The subdomain that the blueprint should be active for, None otherwise.
A dictionary with URL defaults that is added to each and every URL that was defined with the blueprint.
The prefix that should be used for all URLs defined on the blueprint.


A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint’s name.
None


a reference to the blueprint that created this setup state.


as blueprints can be registered multiple times with the application and not everything wants to be registered multiple times on it, this attribute can be used to figure out if the blueprint was registered in the past already.


a dictionary with all options that were passed to the register_blueprint() method.


The subdomain that the blueprint should be active for, None otherwise.


A dictionary with URL defaults that is added to each and every URL that was defined with the blueprint.


The prefix that should be used for all URLs defined on the blueprint.


When your application runs slow, throw some caches in. Well, at least it’s the easiest way to speed up things. What does a cache do? Say you have a function that takes some time to complete but the results would still be good enough if they were 5 minutes old. So then the idea is that you actually put the result of that calculation into a cache for some time.
Flask itself does not provide caching for you, but Flask-Caching, an extension for Flask does. Flask-Caching supports various backends, and it is even possible to develop your own caching backend.


If all other deployment methods do not work, CGI will work for sure. CGI is supported by all major servers but usually has a sub-optimal performance.
This is also the way you can use a Flask application on Google’s App Engine, where execution happens in a CGI-like environment.
Watch Out
Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ ==
'__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to CGI / app engine.
With CGI, you will also have to make sure that your code does not contain any print statements, or that sys.stdout is overridden by something that doesn’t write into the HTTP response.
First you need to create the CGI application file. Let’s call it yourapplication.cgi:
Usually there are two ways to configure the server. Either just copy the .cgi into a cgi-bin (and use mod_rewrite or something similar to rewrite the URL) or let the server point to the file directly.
In Apache for example you can put something like this into the config:
On shared webhosting, though, you might not have access to your Apache config. In this case, a file called .htaccess, sitting in the public directory you want your app to be available, works too but the ScriptAlias directive won’t work in that case:
For more information consult the documentation of your webserver.


Unreleased
Released 2021-05-11
Released 2020-04-03
Released 2019-07-08
Released 2019-07-04
Error handlers for InternalServerError or 500 will always be passed an instance of InternalServerError. If they are invoked due to an unhandled exception, that original exception is now available as e.original_exception rather than being passed directly to the handler. The same is true if the handler is for the base HTTPException. This makes error handler behavior more consistent. #3266
Released 2019-07-04
Released 2019-05-17
Released 2018-05-02
Released 2018-04-29
Released 2018-04-26
The following old deprecated code was removed. #2385
Released 2020-02-10
Released 2018-04-29
Released 2018-04-26
Released 2017-05-16
Released 2017-03-31
Released 2016-12-21, codename Punsch
Released 2016-06-07
Released 2016-05-29, codename Absinthe
Released 2013-06-14
Released 2013-06-13, codename Limoncello
Released 2012-07-01, codename Campari
Released 2012-07-01
Released 2011-09-29, codename Rakija
Released 2011-07-06
Released 2011-06-29
Released 2011-06-28, codename Grappa
Released 2010-12-31
Released 2010-07-27, codename Whisky
Released 2010-07-15
Released 2010-07-06
Released 2010-07-06, codename Calvados
Released 2010-06-18, codename Rakia
Released 2010-05-28
Released 2010-05-28, codename Schnaps
Released 2010-05-12, codename J?germeister
Released 2010-04-16


Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config.
Either you can fill the config from a config file:
Or alternatively you can define the configuration options in the module that calls from_object() or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:
In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application.
Probably the most interesting way to load configurations is from an environment variable pointing to a file:
In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:
On windows use set instead.
None
Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:
bool. True if able to load config, False otherwise.
bool
Update the values in the config from a file that is loaded using the load parameter. The loaded data is passed to the from_mapping() method.
bool
New in version 2.0.
Updates the config like update() ignoring items with non-upper keys.
New in version 0.11.
bool
Updates the values from the given object. An object can be of one of the following two types:
Objects are usually either modules or classes. from_object() loads only the uppercase attributes of the module/class. A dict object will not work with from_object() because the keys of a dict are not attributes of the dict class.
Example of module-based configuration:
Nothing is done to the object before loading. If the object is a class and has @property attributes, it needs to be instantiated before being passed to this method.
You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with from_pyfile() and ideally from a location not within the package because the package might be installed system wide.
See Development / Production for an example of class-based configuration using from_object().
obj (Union[object, str]) – an import name or object
None
Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the from_object() function.
bool
New in version 0.7: silent parameter.
Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:
The resulting dictionary image_store_config would look like:
This is often useful when configuration options map directly to keyword arguments in functions or class constructors.
Dict[str, Any]
New in version 0.11.


Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:
bool. True if able to load config, False otherwise.
bool


Update the values in the config from a file that is loaded using the load parameter. The loaded data is passed to the from_mapping() method.
bool
New in version 2.0.


Updates the config like update() ignoring items with non-upper keys.
New in version 0.11.
bool


Updates the values from the given object. An object can be of one of the following two types:
Objects are usually either modules or classes. from_object() loads only the uppercase attributes of the module/class. A dict object will not work with from_object() because the keys of a dict are not attributes of the dict class.
Example of module-based configuration:
Nothing is done to the object before loading. If the object is a class and has @property attributes, it needs to be instantiated before being passed to this method.
You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with from_pyfile() and ideally from a location not within the package because the package might be installed system wide.
See Development / Production for an example of class-based configuration using from_object().
obj (Union[object, str]) – an import name or object
None


Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the from_object() function.
bool
New in version 0.7: silent parameter.


Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:
The resulting dictionary image_store_config would look like:
This is often useful when configuration options map directly to keyword arguments in functions or class constructors.
Dict[str, Any]
New in version 0.11.


A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. The current session is also included in the copied request context.
Example:
New in version 0.10.
f (Callable) –
Callable


Whether debug mode is enabled. When using flask run to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. The debug attribute maps to this config key. This is enabled when ENV is 'development' and is overridden by the FLASK_DEBUG environment variable. It may not behave as expected if set in code.
Do not enable debug mode when deploying in production.
Default: True if ENV is 'development', or False otherwise.


Serialize an object to JSON written to a file object.
Takes the same arguments as the built-in json.dump(), with some defaults from application configuration.
None
Changed in version 2.0: Writing to a binary file, and the encoding argument, is deprecated and will be removed in Flask 2.1.


Serialize an object to a string of JSON.
Takes the same arguments as the built-in json.dumps(), with some defaults from application configuration.
str
Changed in version 2.0: encoding is deprecated and will be removed in Flask 2.1.
Changed in version 1.0.3: app can be passed directly, rather than requiring an app context for configuration.


What environment the app is running in. Flask and extensions may enable behaviors based on the environment, such as enabling debug mode. The env attribute maps to this config key. This is set by the FLASK_ENV environment variable and may not behave as expected if set in code.
Do not enable development when deploying in production.
Default: 'production'
New in version 1.0.


Replace the characters &, <, >, ', and " in the string with HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML.
If the object has an __html__ method, it is called and the return value is assumed to already be safe for HTML.
s – An object to be converted to a string and escaped.
A Markup string with the escaped text.


Log debugging information tracing how a template file was loaded. This can be useful to figure out why a template was not loaded or the wrong file appears to be loaded.
Default: False


Extensions are extra packages that add functionality to a Flask application. For example, an extension might add support for sending email or connecting to a database. Some extensions add entire new frameworks to help build certain types of applications, like a REST API.
Flask extensions are usually named “Flask-Foo” or “Foo-Flask”. You can search PyPI for packages tagged with Framework :: Flask.
Consult each extension’s documentation for installation, configuration, and usage instructions. Generally, extensions pull their own configuration from app.config and are passed an application instance during initialization. For example, an extension called “Flask-Foo” might be used like this:
While the PyPI contains many Flask extensions, you may not find an extension that fits your need. If this is the case, you can create your own. Read Flask Extension Development to develop your own Flask extension.


FastCGI is a deployment option on servers like nginx, lighttpd, and cherokee; see uWSGI and Standalone WSGI Containers for other options. To use your WSGI application with any of them you will need a FastCGI server first. The most popular one is flup which we will use for this guide. Make sure to have it installed to follow along.
Watch Out
Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ ==
'__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to FastCGI.
First you need to create the FastCGI server file. Let’s call it yourapplication.fcgi:
This is enough for Apache to work, however nginx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. For that to work you need to pass the path to the socket to the WSGIServer:
The path has to be the exact same path you define in the server config.
Save the yourapplication.fcgi file somewhere you will find it again. It makes sense to have that in /var/www/yourapplication or something similar.
Make sure to set the executable bit on that file so that the servers can execute it:
The example above is good enough for a basic Apache deployment but your .fcgi file will appear in your application URL e.g. example.com/yourapplication.fcgi/news/. There are few ways to configure your application so that yourapplication.fcgi does not appear in the URL. A preferable way is to use the ScriptAlias and SetHandler configuration directives to route requests to the FastCGI server. The following example uses FastCgiServer to start 5 instances of the application which will handle all incoming requests:
These processes will be managed by Apache. If you’re using a standalone FastCGI server, you can use the FastCgiExternalServer directive instead. Note that in the following the path is not real, it’s simply used as an identifier to other directives such as AliasMatch:
If you cannot set ScriptAlias, for example on a shared web host, you can use WSGI middleware to remove yourapplication.fcgi from the URLs. Set .htaccess:
Set yourapplication.fcgi:
A basic FastCGI configuration for lighttpd looks like that:
Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to /yourapplication. If you want the application to work in the URL root you have to work around a lighttpd bug with the LighttpdCGIRootFix middleware.
Make sure to apply it only if you are mounting the application the URL root. Also, see the Lighty docs for more information on FastCGI and Python (note that explicitly passing a socket to run() is no longer necessary).
Installing FastCGI applications on nginx is a bit different because by default no FastCGI parameters are forwarded.
A basic Flask FastCGI configuration for nginx looks like this:
This configuration binds the application to /yourapplication. If you want to have it in the URL root it’s a bit simpler because you don’t have to figure out how to calculate PATH_INFO and SCRIPT_NAME:
Since nginx and others do not load FastCGI apps, you have to do it by yourself. Supervisor can manage FastCGI processes. You can look around for other FastCGI process managers or write a script to run your .fcgi file at boot, e.g. using a SysV init.d script. For a temporary solution, you can always run the .fcgi script inside GNU screen. See man screen for details, and note that this is a manual solution which does not persist across system restart:
FastCGI deployments tend to be hard to debug on most web servers. Very often the only thing the server log tells you is something along the lines of “premature end of headers”. In order to debug the application the only thing that can really give you ideas why it breaks is switching to the correct user and executing the application by hand.
This example assumes your application is called application.fcgi and that your web server user is www-data:
In this case the error seems to be “yourapplication” not being on the python path. Common problems are:


Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call get_flashed_messages().
Changed in version 0.3: category parameter added.
None


The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more.
The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an __init__.py file inside) or a standard module (just a .py file).
For more information about resource loading, see open_resource().
Usually you create a Flask instance in your main module or in the __init__.py file of your package like this:
About the First Parameter
The idea of the first parameter is to give Flask an idea of what belongs to your application. This name is used to find resources on the filesystem, can be used by extensions to improve debugging information and a lot more.
So it’s important what you provide there. If you are using a single module, __name__ is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package there.
For example if your application is defined in yourapplication/app.py you should create it with one of the two versions below:
Why is that? The application will work even with __name__, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application. For example the Flask-SQLAlchemy extension will look for the code in your application that triggered an SQL query in debug mode. If the import name is not properly set up, that debugging information is lost. (For example it would only pick up SQL queries in yourapplication.app and not yourapplication.views.frontend)
New in version 1.0: The host_matching and static_host parameters were added.
New in version 1.0: The subdomain_matching parameter was added. Subdomain matching needs to be enabled manually now. Setting SERVER_NAME does not implicitly enable it.
New in version 0.11: The root_path parameter was added.
New in version 0.8: The instance_path and instance_relative_config parameters were added.
New in version 0.7: The static_url_path, static_folder, and template_folder parameters were added.
Register a custom template filter. Works exactly like the template_filter() decorator.
None
Register a custom template global function. Works exactly like the template_global() decorator.
New in version 0.10.
None
Register a custom template test. Works exactly like the template_test() decorator.
New in version 0.10.
None
Register a rule for routing incoming requests and building URLs. The route() decorator is a shortcut to call this with the view_func argument. These are equivalent:
See URL Route Registrations.
The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn’t passed. An error will be raised if a function has already been registered for the endpoint.
The methods parameter defaults to ["GET"]. HEAD is always added automatically, and OPTIONS is added automatically by default.
view_func does not necessarily need to be passed, but if the rule should participate in routing an endpoint name must be associated with a view function at some point with the endpoint() decorator.
If view_func has a required_methods attribute, those methods are added to the passed and automatic methods. If it has a provide_automatic_methods attribute, it is used as the default if the parameter is not passed.
None
Register a function to run after each request to this object.
The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent.
If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request() for that.
f (Callable[[Response], Response]) –
Callable[[Response], Response]
A data structure of functions to call at the end of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the after_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
Create an AppContext. Use as a with block to push the context, which will make current_app point at this application.
An application context is automatically pushed by RequestContext.push() when handling a request, and when running a CLI command. Use this to manually create a context outside of these situations.
See The Application Context.
New in version 0.9.
flask.ctx.AppContext
alias of flask.ctx._AppCtxGlobals
Return a sync function that will run the coroutine function.
Override this method to change how the app converts async code to be synchronously callable.
New in version 2.0.
func (Callable[[...], Coroutine]) –
Callable[[…], Any]
Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named instance next to your main file or the package.
New in version 0.8.
str
Registers a function to be run before the first request to this instance of the application.
The function will be called without any arguments and its return value is ignored.
New in version 0.8.
f (Callable[[], None]) –
Callable[[], None]
A list of functions that will be called at the beginning of the first request to this instance. To register a function, use the before_first_request() decorator.
New in version 0.8.
Register a function to run before each request.
For example, this can be used to open a database connection, or to load the logged in user from the session.
The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped.
f (Callable[[], None]) –
Callable[[], None]
A data structure of functions to call at the beginning of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the before_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
Maps registered blueprint names to blueprint objects. The dict retains the order the blueprints were registered in. Blueprints can be registered multiple times, this dict does not track how often they were attached.
New in version 0.7.
The Click command group for registering CLI commands for this object. The commands are available from the flask command once the application has been discovered and blueprints have been registered.
The configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.
alias of flask.config.Config
Registers a template context processor function.
f (Callable[[], Dict[str, Any]]) –
Callable[[], Dict[str, Any]]
Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It’s discouraged to override this function. Instead one should override the jinja_loader() function instead.
The global loader dispatches between the loaders of the application and the individual blueprints.
New in version 0.7.
flask.templating.DispatchingJinjaLoader
Create the Jinja environment based on jinja_options and the various Jinja-related methods of the app. Changing jinja_options after this will have no effect. Also adds Flask-related globals and filters to the environment.
Changed in version 0.11: Environment.auto_reload set in accordance with TEMPLATES_AUTO_RELOAD configuration option.
New in version 0.5.
flask.templating.Environment
Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly.
Changed in version 1.0: SERVER_NAME no longer implicitly enables subdomain matching. Use subdomain_matching instead.
Changed in version 0.9: This can now also be called without a request object when the URL adapter is created for the application context.
New in version 0.6.
request (Optional[flask.wrappers.Request]) –
Optional[werkzeug.routing.MapAdapter]
Whether debug mode is enabled. When using flask run to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. This maps to the DEBUG config key. This is enabled when env is 'development' and is overridden by the FLASK_DEBUG environment variable. It may not behave as expected if set in code.
Do not enable debug mode when deploying in production.
Default: True if env is 'development', or False otherwise.
Default configuration parameters.
Shortcut for route() with methods=["DELETE"].
New in version 2.0.
Callable
Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call make_response().
Changed in version 0.7: This no longer does the exception handling, this code was moved to the new full_dispatch_request().
Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]
Called right before the application context is popped.
When handling a request, the application context is popped after the request context. See do_teardown_request().
This calls all functions decorated with teardown_appcontext(). Then the appcontext_tearing_down signal is sent.
This is called by AppContext.pop().
New in version 0.9.
exc (Optional[BaseException]) –
None
Called after the request is dispatched and the response is returned, right before the request context is popped.
This calls all functions decorated with teardown_request(), and Blueprint.teardown_request() if a blueprint handled the request. Finally, the request_tearing_down signal is sent.
This is called by RequestContext.pop(), which may be delayed during testing to maintain access to resources.
exc (Optional[BaseException]) – An unhandled exception raised while dispatching the request. Detected from the current exception information if not passed. Passed to each teardown function.
None
Changed in version 0.9: Added the exc argument.
Decorate a view function to register it for the given endpoint. Used if a rule is added without a view_func with add_url_rule().
endpoint (str) – The endpoint name to associate with the view function.
Callable
Ensure that the function is synchronous for WSGI workers. Plain def functions are returned as-is. async def functions are wrapped to run and wait for the response.
Override this method to change how the app runs async views.
New in version 2.0.
func (Callable) –
Callable
What environment the app is running in. Flask and extensions may enable behaviors based on the environment, such as enabling debug mode. This maps to the ENV config key. This is set by the FLASK_ENV environment variable and may not behave as expected if set in code.
Do not enable development when deploying in production.
Default: 'production'
A data structure of registered error handlers, in the format {scope: {code: {class: handler}}}`. The scope key is the name of a blueprint the handlers are active for, or None for all requests. The code key is the HTTP status code for HTTPException, or None for other exceptions. The innermost dictionary maps exception classes to handler functions.
To register an error handler, use the errorhandler() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
Register a function to handle errors by code or exception class.
A decorator that is used to register a function given an error code. Example:
You can also register handlers for arbitrary exceptions:
New in version 0.7: Use register_error_handler() instead of modifying error_handler_spec directly, for application wide error handlers.
New in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the HTTPException class.
code_or_exception (Union[Type[Exception], int]) – the code as integer for the handler, or an arbitrary exception
Callable
a place where extensions can store application specific state. For example this is where an extension could store database engines and similar things.
The key must match the name of the extension module. For example in case of a “Flask-Foo” extension in flask_foo, the key would be 'foo'.
New in version 0.7.
Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling.
New in version 0.7.
flask.wrappers.Response
Shortcut for route() with methods=["GET"].
New in version 2.0.
Callable
Used by send_file() to determine the max_age cache value for a given file path if it wasn’t passed.
By default, this returns SEND_FILE_MAX_AGE_DEFAULT from the configuration of current_app. This defaults to None, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable.
Changed in version 2.0: The default configuration is None instead of 12 hours.
New in version 0.9.
filename (str) –
Optional[int]
This attribute is set to True if the application started handling the first request.
New in version 0.8.
Handle an exception that did not have an error handler associated with it, or that was raised from an error handler. This always causes a 500 InternalServerError.
Always sends the got_request_exception signal.
If propagate_exceptions is True, such as in debug mode, the error will be re-raised so that the debugger can display it. Otherwise, the original exception is logged, and an InternalServerError is returned.
If an error handler is registered for InternalServerError or 500, it will be used. For consistency, the handler will always receive the InternalServerError. The original unhandled exception is available as e.original_exception.
Changed in version 1.1.0: Always passes the InternalServerError instance to the handler, setting original_exception to the unhandled error.
Changed in version 1.1.0: after_request functions and other finalization is done even for the default 500 response when there is no handler.
New in version 0.3.
e (Exception) –
flask.wrappers.Response
Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.
Changed in version 1.0.3: RoutingException, used internally for actions such as slash redirects during routing, is not passed to error handlers.
Changed in version 1.0: Exceptions are looked up by code and by MRO, so HTTPExcpetion subclasses can be handled with a catch-all handler for the base HTTPException.
New in version 0.3.
e (werkzeug.exceptions.HTTPException) –
Union[werkzeug.exceptions.HTTPException, Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]
Handle BuildError on url_for().
str
This method is called whenever an exception occurs that should be handled. A special case is HTTPException which is forwarded to the handle_http_exception() method. This function will either return a response value or reraise the exception with the same traceback.
Changed in version 1.0: Key errors raised from request data like form show the bad key in debug mode rather than a generic bad request message.
New in version 0.7.
e (Exception) –
Union[werkzeug.exceptions.HTTPException, Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]
True if static_folder is set.
New in version 0.5.
The name of the package or module that this object belongs to. Do not change this once it is set by the constructor.
Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building.
New in version 0.7.
None
Holds the path to the instance folder.
New in version 0.8.
Iterates over all blueprints by the order they were registered.
New in version 0.11.
ValuesView[Blueprint]
The Jinja environment used to load templates.
The environment is created the first time this property is accessed. Changing jinja_options after that will have no effect.
alias of flask.templating.Environment
The Jinja loader for this object’s templates. By default this is a class jinja2.loaders.FileSystemLoader to template_folder if it is set.
New in version 0.5.
Options that are passed to the Jinja environment in create_jinja_environment(). Changing these options after the environment is created (accessing jinja_env) will have no effect.
Changed in version 1.1.0: This is a dict instead of an ImmutableDict to allow easier configuration.
alias of flask.json.JSONDecoder
alias of flask.json.JSONEncoder
Logs an exception. This is called by handle_exception() if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the logger.
New in version 0.8.
exc_info (Union[Tuple[type, BaseException, types.TracebackType], Tuple[None, None, None]]) –
None
A standard Python Logger for the app, with the same name as name.
In debug mode, the logger’s level will be set to DEBUG.
If there are no handlers configured, a default handler will be added. See Logging for more information.
Changed in version 1.1.0: The logger takes the same name as name rather than hard-coding "flask.app".
Changed in version 1.0.0: Behavior was simplified. The logger is always named "flask.app". The level is only set during configuration, it doesn’t check app.debug each time. Only one format is used, not different ones depending on app.debug. No handlers are removed, and a handler is only added if no handlers are already configured.
New in version 0.3.
Used to create the config attribute by the Flask constructor. The instance_relative parameter is passed in from the constructor of Flask (there named instance_relative_config) and indicates if the config should be relative to the instance path or the root path of the application.
New in version 0.8.
instance_relative (bool) –
flask.config.Config
This method is called to create the default OPTIONS response. This can be changed through subclassing to change the default behavior of OPTIONS responses.
New in version 0.7.
flask.wrappers.Response
Convert the return value from a view function to an instance of response_class.
rv (Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], WSGIApplication]) –
the return value from the view function. The view function must return a response. Returning None, or the view ending without returning, is not allowed. The following types are allowed for view_rv:
A response object is created with the string encoded to UTF-8 as the body.
A response object is created with the bytes as the body.
A dictionary that will be jsonify’d before being returned.
Either (body, status, headers), (body, status), or (body, headers), where body is any of the other types allowed here, status is a string or an integer, and headers is a dictionary or a list of (key, value) tuples. If body is a response_class instance, status overwrites the exiting value and headers are extended.
The object is returned unchanged.
The object is coerced to response_class.
The function is called as a WSGI application. The result is used to create a response object.
flask.wrappers.Response
Changed in version 0.9: Previously a tuple was interpreted as the arguments for the response object.
Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors.
New in version 0.11.
dict
The name of the application. This is usually the import name with the difference that it’s guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value.
New in version 0.8.
Opens a resource from the application’s instance folder (instance_path). Otherwise works like open_resource(). Instance resources can also be opened for writing.
IO
Open a resource file relative to root_path for reading.
For example, if the file schema.sql is next to the file app.py where the Flask app is defined, it can be opened with:
IO
Shortcut for route() with methods=["PATCH"].
New in version 2.0.
Callable
A timedelta which is used to set the expiration date of a permanent session. The default is 31 days which makes a permanent session survive for roughly one month.
This attribute can also be configured from the config with the PERMANENT_SESSION_LIFETIME configuration key. Defaults to timedelta(days=31)
Shortcut for route() with methods=["POST"].
New in version 2.0.
Callable
Called before the request is dispatched. Calls url_value_preprocessors registered with the app and the current blueprint (if any). Then calls before_request_funcs registered with the app and the blueprint.
If any before_request() handler returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped.
Optional[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]]
Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTION configuration value in case it’s set, otherwise a sensible default is returned.
New in version 0.7.
Can be overridden in order to modify the response object before it’s sent to the WSGI server. By default this will call all the after_request() decorated functions.
Changed in version 0.5: As of Flask 0.5 the functions registered for after request execution are called in reverse order of registration.
response (flask.wrappers.Response) – a response_class object.
a new response object or the same, has to be an instance of response_class.
flask.wrappers.Response
Returns the value of the PROPAGATE_EXCEPTIONS configuration value in case it’s set, otherwise a sensible default is returned.
New in version 0.7.
Shortcut for route() with methods=["PUT"].
New in version 2.0.
Callable
Register a Blueprint on the application. Keyword arguments passed to this method will override the defaults set on the blueprint.
Calls the blueprint’s register() method after recording the blueprint in the application’s blueprints.
None
New in version 0.7.
Alternative error attach function to the errorhandler() decorator that is more straightforward to use for non decorator usage.
New in version 0.7.
None
alias of flask.wrappers.Request
Create a RequestContext representing a WSGI environment. Use a with block to push the context, which will make request point at this request.
See The Request Context.
Typically you should not call this from your own code. A request context is automatically pushed by the wsgi_app() when handling a request. Use test_request_context() to create an environment and context instead of this method.
environ (dict) – a WSGI environment
flask.ctx.RequestContext
alias of flask.wrappers.Response
Absolute path to the package on the filesystem. Used to look up resources contained in the package.
Decorate a view function to register it with the given URL rule and options. Calls add_url_rule(), which has more details about the implementation.
See URL Route Registrations.
The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn’t passed.
The methods parameter defaults to ["GET"]. HEAD and OPTIONS are added automatically.
Callable
Runs the application on a local development server.
Do not use run() in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see Deployment Options for WSGI server recommendations.
If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened.
If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass use_evalex=False as parameter. This will keep the debugger’s traceback screen active, but disable code execution.
It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the flask command line script’s run support.
Keep in Mind
Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke run() with debug=True and use_reloader=False. Setting use_debugger to True without being in debug mode won’t catch any exceptions because there won’t be any to catch.
None
Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from .env and .flaskenv files.
If set, the FLASK_ENV and FLASK_DEBUG environment variables will override env and debug.
Threaded mode is enabled by default.
Changed in version 0.10: The default port is now picked from the SERVER_NAME variable.
If a secret key is set, cryptographic components can use this to sign cookies and other things. Set this to a complex random value when you want to use the secure cookie for instance.
This attribute can also be configured from the config with the SECRET_KEY configuration key. Defaults to None.
Returns True if autoescaping should be active for the given template name. If no template name is given, returns True.
New in version 0.5.
filename (str) –
bool
A timedelta or number of seconds which is used as the default max_age for send_file(). The default is None, which tells the browser to use conditional requests instead of a timed cache.
Configured with the SEND_FILE_MAX_AGE_DEFAULT configuration key.
Changed in version 2.0: Defaults to None instead of 12 hours.
The view function used to serve files from static_folder. A route is automatically registered for this view at static_url_path if static_folder is set.
New in version 0.5.
filename (str) –
Response
The secure cookie uses this for the name of the session cookie.
This attribute can also be configured from the config with the SESSION_COOKIE_NAME configuration key. Defaults to 'session'
the session interface to use. By default an instance of SecureCookieSessionInterface is used here.
New in version 0.8.
Registers a shell context processor function.
New in version 0.11.
f (Callable) –
Callable
A list of shell context processor functions that should be run when a shell context is created.
New in version 0.11.
This is called to figure out if an error should be ignored or not as far as the teardown system is concerned. If this function returns True then the teardown handlers will not be passed the error.
New in version 0.10.
error (Optional[BaseException]) –
bool
The absolute path to the configured static folder. None if no static folder is set.
The URL prefix that the static route will be accessible from.
If it was not configured during init, it is derived from static_folder.
Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped.
Example:
When ctx.pop() is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests.
Since a request context typically also manages an application context it would also be called when you pop a request context.
When a teardown function was called because of an unhandled exception it will be passed an error object. If an errorhandler() is registered, it will handle the exception and the teardown will not receive it.
The return values of teardown functions are ignored.
New in version 0.9.
f (Callable[[Optional[BaseException]], flask.wrappers.Response]) –
Callable[[Optional[BaseException]], flask.wrappers.Response]
A list of functions that are called when the application context is destroyed. Since the application context is also torn down if the request ends this is the place to store code that disconnects from databases.
New in version 0.9.
Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed.
Example:
When ctx.pop() is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests.
Teardown functions must avoid raising exceptions, since they . If they execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors.
When a teardown function was called because of an exception it will be passed an error object.
The return values of teardown functions are ignored.
Debug Note
In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable.
f (Callable[[Optional[BaseException]], Response]) –
Callable[[Optional[BaseException]], Response]
A data structure of functions to call at the end of each request even if an exception is raised, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the teardown_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
A data structure of functions to call to pass extra context values when rendering templates, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the context_processor() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:
name (Optional[str]) – the optional name of the filter, otherwise the function name will be used.
Callable
The path to the templates folder, relative to root_path, to add to the template loader. None if templates should not be added.
A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:
New in version 0.10.
name (Optional[str]) – the optional name of the global function, otherwise the function name will be used.
Callable
A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example:
New in version 0.10.
name (Optional[str]) – the optional name of the test, otherwise the function name will be used.
Callable
Reload templates when they are changed. Used by create_jinja_environment().
This attribute can be configured with TEMPLATES_AUTO_RELOAD. If not set, it will be enabled in debug mode.
New in version 1.0: This property was added but the underlying config and behavior already existed.
Create a CLI runner for testing CLI commands. See Testing CLI Commands.
Returns an instance of test_cli_runner_class, by default FlaskCliRunner. The Flask app object is passed as the first argument.
New in version 1.0.
kwargs (Any) –
FlaskCliRunner
The CliRunner subclass, by default FlaskCliRunner that is used by test_cli_runner(). Its __init__ method should take a Flask app object as the first argument.
New in version 1.0.
Creates a test client for this application. For information about unit testing head over to Testing Flask Applications.
Note that if you are testing for assertions or exceptions in your application code, you must set app.testing = True in order for the exceptions to propagate to the test client. Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client. See the testing attribute. For example:
The test client can be used in a with block to defer the closing down of the context until the end of the with block. This is useful if you want to access the context locals for testing:
Additionally, you may pass optional keyword arguments that will then be passed to the application’s test_client_class constructor. For example:
See FlaskClient for more information.
Changed in version 0.11: Added **kwargs to support passing additional keyword arguments to the constructor of test_client_class.
New in version 0.7: The use_cookies parameter was added as well as the ability to override the client to be used by setting the test_client_class attribute.
Changed in version 0.4: added support for with block usage for the client.
FlaskClient
the test client that is used with when test_client is used.
New in version 0.7.
Create a RequestContext for a WSGI environment created from the given values. This is mostly useful during testing, where you may want to run a function that uses request data without dispatching a full request.
See The Request Context.
Use a with block to push the context, which will make request point at the request for the created environment.
When using the shell, it may be easier to push and pop the context manually to avoid indentation.
Takes the same arguments as Werkzeug’s EnvironBuilder, with some defaults from the application. See the linked Werkzeug docs for most of the available arguments. Flask-specific behavior is listed here.
flask.ctx.RequestContext
The testing flag. Set this to True to enable the test mode of Flask extensions (and in the future probably also Flask itself). For example this might activate test helpers that have an additional runtime cost which should not be enabled by default.
If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the default it’s implicitly enabled.
This attribute can also be configured from the config with the TESTING configuration key. Defaults to False.
Checks if an HTTP exception should be trapped or not. By default this will return False for all exceptions except for a bad request key error if TRAP_BAD_REQUEST_ERRORS is set to True. It also returns True if TRAP_HTTP_EXCEPTIONS is set to True.
This is called for all HTTP exceptions raised by a view function. If it returns True for any exception the error handler for this exception is not called and it shows up as regular exception in the traceback. This is helpful for debugging implicitly raised HTTP exceptions.
Changed in version 1.0: Bad request errors are not trapped by default in debug mode.
New in version 0.8.
e (Exception) –
bool
Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key.
context (dict) – the context as a dictionary that is updated in place to add extra variables.
None
A list of functions that are called when url_for() raises a BuildError. Each function registered here is called with error, endpoint and values. If a function returns None or raises a BuildError the next function is tried.
New in version 0.9.
A data structure of functions to call to modify the keyword arguments when generating URLs, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the url_defaults() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place.
f (Callable[[str, dict], None]) –
Callable[[str, dict], None]
The Map for this instance. You can use this to change the routing converters after the class was created but before any routes are connected. Example:
alias of werkzeug.routing.Map
alias of werkzeug.routing.Rule
Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request() functions.
The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in g rather than pass it to every view.
The function is passed the endpoint name and values dict. The return value is ignored.
f (Callable[[Optional[str], Optional[dict]], None]) –
Callable[[Optional[str], Optional[dict]], None]
A data structure of functions to call to modify the keyword arguments passed to the view function, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the url_value_preprocessor() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
Enable this if you want to use the X-Sendfile feature. Keep in mind that the server has to support this. This only affects files sent with the send_file() method.
New in version 0.2.
This attribute can also be configured from the config with the USE_X_SENDFILE configuration key. Defaults to False.
A dictionary mapping endpoint names to view functions.
To register a view function, use the route() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.
The actual WSGI application. This is not implemented in __call__() so that middlewares can be applied without losing a reference to the app object. Instead of doing this:
It’s a better idea to do this instead:
Then you still have the original application object around and can continue to call methods on it.
Changed in version 0.7: Teardown events for the request and app contexts are called even if an unhandled error occurs. Other events may not be called depending on when an error occurs during dispatch. See Callbacks and Errors.
Any


Register a custom template filter. Works exactly like the template_filter() decorator.
None


Register a custom template global function. Works exactly like the template_global() decorator.
New in version 0.10.
None


Register a custom template test. Works exactly like the template_test() decorator.
New in version 0.10.
None


Register a rule for routing incoming requests and building URLs. The route() decorator is a shortcut to call this with the view_func argument. These are equivalent:
See URL Route Registrations.
The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn’t passed. An error will be raised if a function has already been registered for the endpoint.
The methods parameter defaults to ["GET"]. HEAD is always added automatically, and OPTIONS is added automatically by default.
view_func does not necessarily need to be passed, but if the rule should participate in routing an endpoint name must be associated with a view function at some point with the endpoint() decorator.
If view_func has a required_methods attribute, those methods are added to the passed and automatic methods. If it has a provide_automatic_methods attribute, it is used as the default if the parameter is not passed.
None


Register a function to run after each request to this object.
The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent.
If a function raises an exception, any remaining after_request functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use teardown_request() for that.
f (Callable[[Response], Response]) –
Callable[[Response], Response]


A data structure of functions to call at the end of each request, in the format {scope: [functions]}. The scope key is the name of a blueprint the functions are active for, or None for all requests.
To register a function, use the after_request() decorator.
This data structure is internal. It should not be modified directly and its format may change at any time.