This signal is sent when an application context is popped. The sender is the application. This usually falls in line with the appcontext_tearing_down signal.
New in version 0.10.


This signal is sent when an application context is pushed. The sender is the application. This is usually useful for unittests in order to temporarily hook in information. For instance it can be used to set a resource early onto the g object.
Example usage:
And in the testcode:
New in version 0.10.


This signal is sent when the app context is tearing down. This is always called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on.
Example subscriber:
This will also be passed an exc keyword argument that has a reference to the exception that caused the teardown if there was one.


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


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.


Run a local development server.
This server is for development purposes only. It does not provide the stability, security, or performance of production WSGI servers.
The reloader and debugger are enabled by default if FLASK_ENV=development or FLASK_DEBUG=1.
Any


Run an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to its configuration.
This is useful for executing small snippets of management code without having to manually configure the application.
Any


The configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.


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]


A proxy to the application handling the current request. This is useful to access the application without needing to import it, or if it can’t be imported, such as when using the application factory pattern or in blueprints and extensions.
This is only available when an application context is pushed. This happens automatically during requests and CLI commands. It can be controlled manually with app_context().
This is a proxy. See Notes On Proxies for more information.


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'


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.


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


A namespace object that can store data during an application context. This is an instance of Flask.app_ctx_globals_class, which defaults to ctx._AppCtxGlobals.
This is a good place to store resources during a request. During testing, you can use the Faking Resources and Context pattern to pre-configure such resources.
This is a proxy. See Notes On Proxies for more information.
Changed in version 0.10: Bound to the application context instead of the request context.


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 signal is sent when an unhandled exception happens during request processing, including when debugging. The exception is passed to the subscriber as exception.
This signal is not sent for HTTPException, or other exceptions that have error handlers registered, unless the exception was raised from an error handler.
This example shows how to do some extra logging if a theoretical SecurityException was raised:


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]


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]


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]


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.


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


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


This signal is sent when the application is flashing a message. The messages is sent as message keyword argument and the category as category.
Example subscriber:
New in version 0.10.


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]]


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


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


To access incoming request data, you can use the global request object. Flask parses incoming request data for you and gives you access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment.
This is a proxy. See Notes On Proxies for more information.
The request object is an instance of a 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


This signal is sent right before the response is sent to the client. It is passed the response to be sent named response.
Example subscriber:


This signal is sent when the request context is set up, before any request processing happens. Because the request context is already bound, the subscriber can access the request with the standard global proxies such as request.
Example subscriber:


This signal is sent when the request is tearing down. This is always called, even if an exception is caused. Currently functions listening to this signal are called after the regular teardown handlers, but this is not something you can rely on.
Example subscriber:
As of Flask 0.9, this will also be passed an exc keyword argument that has a reference to the exception that caused the teardown if there was one.


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


True if the signaling system is available. This is the case when blinker is installed.


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


This signal is sent when a template was successfully rendered. The signal is invoked with the instance of the template as template and the context as dictionary (named context).
Example subscriber:


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


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.


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 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.


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


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.


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.


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:


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


The internal LocalStack that holds AppContext instances. Typically, the current_app and g proxies should be accessed instead of the stack. Extensions can access the contexts on the stack as a namespace to store data.
New in version 0.9.


The internal LocalStack that holds RequestContext instances. Typically, the request and session proxies should be accessed instead of the stack. It may be useful to access the stack in extension code.
The following attributes are always present on each layer of the stack:
the active Flask application.
the URL adapter that was used to match the request.
the current request object.
the active session object.
an object with all the attributes of the flask.g object.
an internal cache for the flashed messages.
Example usage:


Works like a regular Werkzeug test client but has some knowledge about how Flask works to defer the cleanup of the request context stack to the end of a with body when used in a with statement. For general information about how to use this class refer to werkzeug.test.Client.
Changed in version 0.12: app.test_client() includes preset default environment, which can be set after instantiation of the app.test_client() object in client.environ_base.
Basic usage is outlined in the Testing Flask Applications chapter.
None
Generate an environ dict from the given arguments, make a request to the application using it, and return the response.
Response
Changed in version 2.0: as_tuple is deprecated and will be removed in Werkzeug 2.1. Use TestResponse.request and request.environ instead.
Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed.
Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper.
Changed in version 0.5: Added the follow_redirects parameter.
When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back.
Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as test_request_context() which are directly passed through.
Generator[flask.sessions.SessionMixin, None, None]


Generate an environ dict from the given arguments, make a request to the application using it, and return the response.
Response
Changed in version 2.0: as_tuple is deprecated and will be removed in Werkzeug 2.1. Use TestResponse.request and request.environ instead.
Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed.
Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper.
Changed in version 0.5: Added the follow_redirects parameter.


When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back.
Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as test_request_context() which are directly passed through.
Generator[flask.sessions.SessionMixin, None, None]


A CliRunner for testing a Flask app’s CLI commands. Typically created using test_cli_runner(). See Testing CLI Commands.
None
Invokes a CLI command in an isolated environment. See CliRunner.invoke for full method documentation. See Testing CLI Commands for examples.
If the obj argument is not given, passes an instance of ScriptInfo that knows how to load the Flask app being tested.
a Result object.
Any


Invokes a CLI command in an isolated environment. See CliRunner.invoke for full method documentation. See Testing CLI Commands for examples.
If the obj argument is not given, passes an instance of ScriptInfo that knows how to load the Flask app being tested.
a Result object.
Any


Special subclass of the AppGroup group that supports loading more commands from the configured Flask app. Normally a developer does not have to interface with this class but there are some very advanced use cases for which it makes sense to create an instance of this. see Custom Scripts.
Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from .env and .flaskenv files.
Given a context and a command name, this returns a Command object if it exists or returns None.
Returns a list of subcommand names in the order they should appear.
This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, SystemExit needs to be caught.
This method is also available by directly calling the instance of a Command.
Changed in version 8.0: When taking arguments from sys.argv on Windows, glob patterns, user dir, and env vars are expanded.
Changed in version 3.0: Added the standalone_mode parameter.


Given a context and a command name, this returns a Command object if it exists or returns None.


Returns a list of subcommand names in the order they should appear.


This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, SystemExit needs to be caught.
This method is also available by directly calling the instance of a Command.
Changed in version 8.0: When taking arguments from sys.argv on Windows, glob patterns, user dir, and env vars are expanded.
Changed in version 3.0: Added the standalone_mode parameter.


Read this before you get started with Flask. This hopefully answers some questions about the purpose and goals of the project, and when you should or should not be using it.
“Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The “micro” in microframework means Flask aims to keep the core simple but extensible. Flask won’t make many decisions for you, such as what database to use. Those decisions that it does make, such as what templating engine to use, are easy to change. Everything else is up to you, so that Flask can be everything you need and nothing you don’t.
By default, Flask does not include a database abstraction layer, form validation or anything else where different libraries already exist that can handle that. Instead, Flask supports extensions to add such functionality to your application as if it was implemented in Flask itself. Numerous extensions provide database integration, form validation, upload handling, various open authentication technologies, and more. Flask may be “micro”, but it’s ready for production use on a variety of needs.
Flask has many configuration values, with sensible defaults, and a few conventions when getting started. By convention, templates and static files are stored in subdirectories within the application’s Python source tree, with the names templates and static respectively. While this can be changed, you usually don’t have to, especially when getting started.
Once you have Flask up and running, you’ll find a variety of extensions available in the community to integrate your project for production.
As your codebase grows, you are free to make the design decisions appropriate for your project. Flask will continue to provide a very simple glue layer to the best that Python has to offer. You can implement advanced patterns in SQLAlchemy or another database tool, introduce non-relational data persistence as appropriate, and take advantage of framework-agnostic tools built for WSGI, the Python web interface.
Flask includes many hooks to customize its behavior. Should you need more customization, the Flask class is built for subclassing. If you are interested in that, check out the Becoming Big chapter. If you are curious about the Flask design principles, head over to the section about Design Decisions in Flask.


Pulls all flashed messages from the session and returns them. Further calls in the same request to the function will return the same messages. By default just the messages are returned, but when with_categories is set to True, the return value will be a list of tuples in the form (category, message) instead.
Filter the flashed messages to one or more categories by providing those categories in category_filter. This allows rendering categories in separate html blocks. The with_categories and category_filter arguments are distinct:
See Message Flashing for examples.
Changed in version 0.9: category_filter parameter added.
Changed in version 0.3: with_categories parameter added.
Union[List[str], List[Tuple[str, str]]]


Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named _cider.html with the following contents:
You can access this from Python code like this:
New in version 0.2.
Any


Works like has_request_context() but for the application context. You can also just do a boolean check on the current_app object instead.
New in version 0.9.
bool


If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable.
Alternatively you can also just test any of the context bound objects (such as request or g) for truthness:
New in version 0.7.
bool


We recommend using the latest version of Python. Flask supports Python 3.6 and newer.
These distributions will be installed automatically when installing Flask.
These distributions will not be installed automatically. Flask will detect and use them if you install them.
Use a virtual environment to manage the dependencies for your project, both in development and in production.
What problem does a virtual environment solve? The more Python projects you have, the more likely it is that you need to work with different versions of Python libraries, or even Python itself. Newer versions of libraries for one project can break compatibility in another project.
Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system’s packages.
Python comes bundled with the venv module to create virtual environments.
Create a project folder and a venv folder within:
Before you work on your project, activate the corresponding environment:
Your shell prompt will change to show the name of the activated environment.
Within the activated environment, use the following command to install Flask:
Flask is now installed. Check out the Quickstart or go to the Documentation Overview.


The default JSON decoder.
This does not change any behavior from the built-in json.JSONDecoder.
Assign a subclass of this to flask.Flask.json_decoder or flask.Blueprint.json_decoder to override the default.


The default JSON encoder. Handles extra types compared to the built-in json.JSONEncoder.
Assign a subclass of this to flask.Flask.json_encoder or flask.Blueprint.json_encoder to override the default.
Convert o to a JSON serializable type. See json.JSONEncoder.default(). Python does not support overriding how basic types like str or list are serialized, they are handled before this method.
o (Any) –
Any


Convert o to a JSON serializable type. See json.JSONEncoder.default(). Python does not support overriding how basic types like str or list are serialized, they are handled before this method.
o (Any) –
Any


Serialize data to JSON and wrap it in a Response with the application/json mimetype.
Uses dumps() to serialize the data, but args and kwargs are treated as data rather than arguments to json.dumps().
Will return a JSON response like this:
The default output omits indents and spaces after separators. In debug mode or if JSONIFY_PRETTYPRINT_REGULAR is True, the output will be formatted to be easier to read.
Changed in version 0.11: Added support for serializing top-level arrays. This introduces a security risk in ancient browsers. See JSON Security.
New in version 0.2.
Response


The mimetype of jsonify responses.
Default: 'application/json'


jsonify responses will be output with newlines, spaces, and indentation for easier reading by humans. Always enabled in debug mode.
Default: False


Base class for defining type tags for TaggedJSONSerializer.
serializer (TaggedJSONSerializer) –
None
Check if the given value should be tagged by this tag.
value (Any) –
bool
The tag to mark the serialized object with. If None, this tag is only used as an intermediate step during tagging.
Convert the value to a valid JSON type and add the tag structure around it.
value (Any) –
Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
value (Any) –
Any
Convert the JSON representation back to the correct type. The tag will already be removed.
value (Any) –
Any


Check if the given value should be tagged by this tag.
value (Any) –
bool


The tag to mark the serialized object with. If None, this tag is only used as an intermediate step during tagging.


Convert the value to a valid JSON type and add the tag structure around it.
value (Any) –
Any


Convert the Python object to an object that is a valid JSON type. The tag will be added later.
value (Any) –
Any


Convert the JSON representation back to the correct type. The tag will already be removed.
value (Any) –
Any


Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON returned from jsonify will contain Unicode characters. This has security implications when rendering the JSON into JavaScript in templates, and should typically remain enabled.
Default: True


Sort the keys of JSON objects alphabetically. This is useful for caching because it ensures the data is serialized the same way no matter what Python’s hash seed is. While not recommended, you can disable this for a possible performance improvement at the cost of caching.
Default: True


Deserialize an object from JSON read from a file object.
Takes the same arguments as the built-in json.load(), with some defaults from application configuration.
Any
Changed in version 2.0: encoding is deprecated and will be removed in Flask 2.1. The file must be text mode, or binary mode with UTF-8 bytes.


Deserialize an object from a string of JSON.
Takes the same arguments as the built-in json.loads(), with some defaults from application configuration.
Any
Changed in version 2.0: encoding is deprecated and will be removed in Flask 2.1. The data must be a string or UTF-8 bytes.
Changed in version 1.0.3: app can be passed directly, rather than requiring an app context for configuration.


Load “dotenv” files in order of precedence to set environment variables.
If an env var is already set it is not overwritten, so earlier files in the list are preferred over later files.
This is a no-op if python-dotenv is not installed.
path – Load the file at this location instead of searching.
True if a file was loaded.
Changed in version 2.0: When loading the env files, set the default encoding to UTF-8.
Changed in version 1.1.0: Returns False when python-dotenv is not installed, or when the given path isn’t a file.
New in version 1.0.


Flask uses standard Python logging. Messages about your Flask application are logged with app.logger, which takes the same name as app.name. This logger can also be used to log your own messages.
If you don’t configure logging, Python’s default log level is usually ‘warning’. Nothing below the configured level will be visible.
When you want to configure logging for your project, you should do it as soon as possible when the program starts. If app.logger is accessed before logging is configured, it will add a default handler. If possible, configure logging before creating the application object.
This example uses dictConfig() to create a logging configuration similar to Flask’s default, except for all logs:
If you do not configure logging yourself, Flask will add a StreamHandler to app.logger automatically. During requests, it will write to the stream specified by the WSGI server in environ['wsgi.errors'] (which is usually sys.stderr). Outside a request, it will log to sys.stderr.
If you configured logging after accessing app.logger, and need to remove the default handler, you can import and remove it:
When running the application on a remote server for production, you probably won’t be looking at the log messages very often. The WSGI server will probably send log messages to a file, and you’ll only check that file if a user tells you something went wrong.
To be proactive about discovering and fixing bugs, you can configure a logging.handlers.SMTPHandler to send an email when errors and higher are logged.
This requires that you have an SMTP server set up on the same server. See the Python docs for more information about configuring the handler.
Seeing more information about the request, such as the IP address, may help debugging some errors. You can subclass logging.Formatter to inject your own fields that can be used in messages. You can change the formatter for Flask’s default handler, the mail handler defined above, or any other handler.
Other libraries may use logging extensively, and you want to see relevant messages from those logs too. The simplest way to do this is to add handlers to the root logger instead of only the app logger.
Depending on your project, it may be more useful to configure each logger you care about separately, instead of configuring only the root logger.
Werkzeug logs basic request/response information to the 'werkzeug' logger. If the root logger has no handlers configured, Werkzeug adds a StreamHandler to its logger.
Depending on the situation, an extension may choose to log to app.logger or its own named logger. Consult each extension’s documentation for details.


Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.
If view looked like this and you want to add a new header:
You can now do something like this:
This function accepts the very same arguments you can return from a view function. This for example creates a response with a 404 error code:
The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators:
Internally this function does the following things:
New in version 0.6.
args (Any) –
Response


A string that is ready to be safely inserted into an HTML or XML document, either because it was escaped or because it was marked safe.
Passing an object to the constructor converts it to text and wraps it to mark it safe without escaping. To escape the text, use the escape() class method instead.
This implements the __html__() interface that some frameworks use. Passing an object that implements __html__() will wrap the output of that method, marking it safe.
This is a subclass of str. It has the same methods, but escapes their arguments and returns a Markup instance.
Markup
Escape a string. Calls escape() and ensures that for subclasses the correct type is returned.
s (Any) –
markupsafe.Markup
unescape() the markup, remove tags, and normalize whitespace to single spaces.
str
Convert escaped markup back into a text string. This replaces HTML entities with the characters they represent.
str


Escape a string. Calls escape() and ensures that for subclasses the correct type is returned.
s (Any) –
markupsafe.Markup


unescape() the markup, remove tags, and normalize whitespace to single spaces.
str


Convert escaped markup back into a text string. This replaces HTML entities with the characters they represent.
str


Don’t read more than this many bytes from the incoming request data. If not set and the request does not specify a CONTENT_LENGTH, no data will be read for security.
Default: None


Warn if cookie headers are larger than this many bytes. Defaults to 4093. Larger cookies may be silently ignored by browsers. Set to 0 to disable the warning.


A class-based view that dispatches request methods to the corresponding class methods. For example, if you implement a get method, it will be used to handle GET requests.
Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.
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]


Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.
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]


An alias for blinker.base.Namespace if blinker is available, otherwise a dummy class that creates fake signals. This class is available for Flask extensions that want to provide the same fallback system as Flask itself.
Creates a new signal for this namespace if blinker is available, otherwise returns a fake signal that has a send method that will do nothing but will fail with a RuntimeError for all other operations, including connecting.


Creates a new signal for this namespace if blinker is available, otherwise returns a fake signal that has a send method that will do nothing but will fail with a RuntimeError for all other operations, including connecting.


Class used to generate nicer error messages if sessions are not available. Will still allow read-only access to the empty session but fail on setting.
initial (Any) –
None


Marks a function so that an instance of ScriptInfo is passed as first argument to the click callback.
f (click.decorators.F) –
click.decorators.F


If session.permanent is true, the cookie’s expiration will be set this number of seconds in the future. Can either be a datetime.timedelta or an int.
Flask’s default cookie implementation validates that the cryptographic signature is not older than this value.
Default: timedelta(days=31) (2678400 seconds)


Use this scheme for generating external URLs when not in a request context.
Default: 'http'


Don’t pop the request context when an exception occurs. If not set, this is true if DEBUG is true. This allows debuggers to introspect the request data on errors, and should normally not need to be set directly.
Default: None


Exceptions are re-raised rather than being handled by the app’s error handlers. If not set, this is implicitly true if TESTING or DEBUG is enabled.
Default: None


Eager to get started? This page gives a good introduction to Flask. Follow Installation to set up a project and install Flask first.
A minimal Flask application looks something like this:
So what did that code do?
Save it as hello.py or something similar. Make sure to not call your application flask.py because this would conflict with Flask itself.
To run the application, use the flask command or python -m flask. Before you can do that you need to tell your terminal the application to work with by exporting the FLASK_APP environment variable:
Application Discovery Behavior
As a shortcut, if the file is named app.py or wsgi.py, you don’t have to set the FLASK_APP environment variable. See Command Line Interface for more details.
This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see Deployment Options.
Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting.
Externally Visible Server
If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.
If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line:
This tells your operating system to listen on all public IPs.
In case the python -m flask fails or flask does not exist, there are multiple reasons this might be the case. First of all you need to look at the error message.
Versions of Flask older than 0.11 used to have different ways to start the application. In short, the flask command did not exist, and neither did python -m flask. In that case you have two options: either upgrade to newer Flask versions or have a look at Development Server to see the alternative method for running a server.
The FLASK_APP environment variable is the name of the module to import at flask run. In case that module is incorrectly named you will get an import error upon start (or if debug is enabled when you navigate to the application). It will tell you what it tried to import and why it failed.
The most common reason is a typo or because you did not actually create an app object.
The flask run command can do more than just start the development server. By enabling debug mode, the server will automatically reload if code changes, and will show an interactive debugger in the browser if an error occurs during a request.
Warning
The debugger allows executing arbitrary Python code from the browser. It is protected by a pin, but still represents a major security risk. Do not run the development server or debugger in a production environment.
To enable all development features, set the FLASK_ENV environment variable to development before calling flask run.
See also:
When returning HTML (the default response type in Flask), any user-provided values rendered in the output must be escaped to protect from injection attacks. HTML templates rendered with Jinja, introduced later, will do this automatically.
escape(), shown here, can be used manually. It is omitted in most examples for brevity, but you should always be aware of how you’re using untrusted data.
If a user managed to submit the name <script>alert("bad")</script>, escaping causes it to be rendered as text, rather than running the script in the user’s browser.
<name> in the route captures a value from the URL and passes it to the view function. These variable rules are explained below.
Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page.
Use the route() decorator to bind a function to a URL.
You can do more! You can make parts of the URL dynamic and attach multiple rules to a function.
You can add variable sections to a URL by marking sections with <variable_name>. Your function then receives the <variable_name> as a keyword argument. Optionally, you can use a converter to specify the type of the argument like <converter:variable_name>.
Converter types:
string
(default) accepts any text without a slash
int
accepts positive integers
float
accepts positive floating point values
path
like string but also accepts slashes
uuid
accepts UUID strings
The following two rules differ in their use of a trailing slash.
The canonical URL for the projects endpoint has a trailing slash. It’s similar to a folder in a file system. If you access the URL without a trailing slash (/projects), Flask redirects you to the canonical URL with the trailing slash (/projects/).
The canonical URL for the about endpoint does not have a trailing slash. It’s similar to the pathname of a file. Accessing the URL with a trailing slash (/about/) produces a 404 “Not Found” error. This helps keep URLs unique for these resources, which helps search engines avoid indexing the same page twice.
To build a URL to a specific function, use the url_for() function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters.
Why would you want to build URLs using the URL reversing function url_for() instead of hard-coding them into your templates?
For example, here we use the test_request_context() method to try out url_for(). test_request_context() tells Flask to behave as though it’s handling a request even while we use a Python shell. See Context Locals.
Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods.
If GET is present, Flask automatically adds support for the HEAD method and handles HEAD requests according to the HTTP RFC. Likewise, OPTIONS is automatically implemented for you.
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.
To generate URLs for static files, use the special 'static' endpoint name:
The file has to be stored on the filesystem as static/style.css.
Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures the Jinja2 template engine for you automatically.
To render a template you can use the render_template() method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here’s a simple example of how to render a template:
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:
Case 1: a module:
Case 2: a package:
For templates you can use the full power of Jinja2 templates. Head over to the official Jinja2 Template Documentation for more information.
Here is an example template:
Inside templates you also have access to the request, session and g 1 objects as well as the get_flashed_messages() function.
Templates are especially useful if inheritance is used. If you want to know how that works, see Template Inheritance. Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer).
Automatic escaping is enabled, so if name contains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the Markup class or by using the |safe filter in the template. Head over to the Jinja 2 documentation for more examples.
Here is a basic introduction to how the Markup class works:
Changed in version 0.5: Autoescaping is no longer enabled for all templates. The following extensions for templates trigger autoescaping: .html, .htm, .xml, .xhtml. Templates loaded from a string will have autoescaping disabled.
Unsure what that g object is? It’s something in which you can store information for your own needs. See the documentation for flask.g and Using SQLite 3 with Flask.
For web applications it’s crucial to react to the data a client sends to the server. In Flask this information is provided by the global request object. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer is context locals:
Insider Information
If you want to understand how that works and how you can implement tests with context locals, read this section, otherwise just skip it.
Certain objects in Flask are global objects, but not of the usual kind. These objects are actually proxies to objects that are local to a specific context. What a mouthful. But that is actually quite easy to understand.
Imagine the context being the handling thread. A request comes in and the web server decides to spawn a new thread (or something else, the underlying object is capable of dealing with concurrency systems other than threads). When Flask starts its internal request handling it figures out that the current thread is the active context and binds the current application and the WSGI environments to that context (thread). It does that in an intelligent way so that one application can invoke another application without breaking.
So what does this mean to you? Basically you can completely ignore that this is the case unless you are doing something like unit testing. You will notice that code which depends on a request object will suddenly break because there is no request object. The solution is creating a request object yourself and binding it to the context. The easiest solution for unit testing is to use the test_request_context() context manager. In combination with the with statement it will bind a test request so that you can interact with it. Here is an example:
The other possibility is passing a whole WSGI environment to the request_context() method:
The request object is documented in the API section and we will not cover it here in detail (see Request). Here is a broad overview of some of the most common operations. First of all you have to import it from the flask module:
The current request method is available by using the method attribute. To access form data (data transmitted in a POST or PUT request) you can use the form attribute. Here is a full example of the two attributes mentioned above:
What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. You can catch it like a standard KeyError but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.
To access parameters submitted in the URL (?key=value) you can use the args attribute:
We recommend accessing URL parameters with get or by catching the KeyError because users might change the URL and presenting them a 400 bad request page in that case is not user friendly.
For a full list of methods and attributes of the request object, head over to the Request documentation.
You can handle uploaded files with Flask easily. Just make sure not to forget to set the enctype="multipart/form-data" attribute on your HTML form, otherwise the browser will not transmit your files at all.
Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the files attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python file object, but it also has a save() method that allows you to store that file on the filesystem of the server. Here is a simple example showing how that works:
If you want to know how the file was named on the client before it was uploaded to your application, you can access the filename attribute. However please keep in mind that this value can be forged so never ever trust that value. If you want to use the filename of the client to store the file on the server, pass it through the secure_filename() function that Werkzeug provides for you:
For some better examples, see Uploading Files.
To access cookies you can use the cookies attribute. To set cookies you can use the set_cookie method of response objects. The cookies attribute of request objects is a dictionary with all the cookies the client transmits. If you want to use sessions, do not use the cookies directly but instead use the Sessions in Flask that add some security on top of cookies for you.
Reading cookies:
Storing cookies:
Note that cookies are set on response objects. Since you normally just return strings from the view functions Flask will convert them into response objects for you. If you explicitly want to do that you can use the make_response() function and then modify it.
Sometimes you might want to set a cookie at a point where the response object does not exist yet. This is possible by utilizing the Deferred Request Callbacks pattern.
For this also see About Responses.
To redirect a user to another endpoint, use the redirect() function; to abort a request early with an error code, use the abort() function:
This is a rather pointless example because a user will be redirected from the index to a page they cannot access (401 means access denied) but it shows how that works.
By default a black and white error page is shown for each error code. If you want to customize the error page, you can use the errorhandler() decorator:
Note the 404 after the render_template() call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well.
See Handling Application Errors for more details.
The return value from a view function is automatically converted into a response object for you. If the return value is a string it’s converted into a response object with the string as response body, a 200 OK status code and a text/html mimetype. If the return value is a dict, jsonify() is called to produce a response. The logic that Flask applies to converting return values into response objects is as follows:
If you want to get hold of the resulting response object inside the view you can use the make_response() function.
Imagine you have a view like this:
You just need to wrap the return expression with make_response() and get the response object to modify it, then return it:
A common response format when writing an API is JSON. It’s easy to get started writing such an API with Flask. If you return a dict from a view, it will be converted to a JSON response.
Depending on your API design, you may want to create JSON responses for types other than dict. In that case, use the jsonify() function, which will serialize any supported JSON data type. Or look into Flask community extensions that support more complex applications.
In addition to the request object there is also a second object called session which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing.
In order to use sessions you have to set a secret key. Here is how sessions work:
How to generate good secret keys
A secret key should be as random as possible. Your operating system has ways to generate pretty random data based on a cryptographic random generator. Use the following command to quickly generate a value for Flask.secret_key (or SECRET_KEY):
A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. If you are finding some values do not persist across requests, cookies are indeed enabled, and you are not getting a clear error message, check the size of the cookie in your page responses compared to the size supported by web browsers.
Besides the default client-side based sessions, if you want to handle sessions on the server-side instead, there are several Flask extensions that support this.
Good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request. This is usually combined with a layout template to expose the message.
To flash a message use the flash() method, to get hold of the messages you can use get_flashed_messages() which is also available in the templates. See Message Flashing for a full example.
New in version 0.3.
Sometimes you might be in a situation where you deal with data that should be correct, but actually is not. For example you may have some client-side code that sends an HTTP request to the server but it’s obviously malformed. This might be caused by a user tampering with the data, or the client code failing. Most of the time it’s okay to reply with 400 Bad Request in that situation, but sometimes that won’t do and the code has to continue working.
You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you to use.
Here are some example log calls:
The attached logger is a standard logging Logger, so head over to the official logging docs for more information.
See Handling Application Errors.
To add WSGI middleware to your Flask application, wrap the application’s wsgi_app attribute. For example, to apply Werkzeug’s ProxyFix middleware for running behind Nginx:
Wrapping app.wsgi_app instead of app means that app still points at your Flask application, not at the middleware, so you can continue to use and configure app directly.
Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask.
For more on Flask extensions, see Extensions.
Ready to deploy your new Flask app? See Deployment Options.


Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, 307, and 308. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
New in version 0.10: The class used for the Response object can now be passed in.
New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function.
Response


Renders a template from the template folder with the given context.
str


Renders a template from the given template source string with the given context. Template variables will be autoescaped.
str


The request object used by default in Flask. Remembers the matched endpoint and view arguments.
It is what ends up as request. If you want to replace the request object used you can subclass this and set request_class to your subclass.
The request object is a Request subclass and provides all of the attributes Werkzeug defines plus a few Flask specific ones.
None
List of charsets this client supports as CharsetAccept object.
List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at accept_charset.
List of languages this client accepts as LanguageAccept object.
List of mimetypes this client supports as MIMEAccept object.
Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set access_control_allow_headers on the response to indicate which headers are allowed.
Sent with a preflight request to indicate which method will be used for the cross origin request. Set access_control_allow_methods on the response to indicate which methods are allowed.
If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server.
Decorate a function as responder that accepts the request as the last argument. This works like the responder() decorator but the function is passed the request object as the last argument and the request object will be closed automatically:
As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing.
f (Callable[[Request], WSGIApplication]) – the WSGI callable to decorate
a new WSGI callable
WSGIApplication
The parsed URL parameters (the part in the URL after the question mark).
By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important.
The Authorization object in parsed form.
Like url but without the query string.
The name of the current blueprint
A RequestCacheControl object for the incoming cache control headers.
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it.
New in version 0.9.
None
The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.
New in version 0.9.
The Content-Length entity-header field indicates the size of the entity-body in bytes or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)
New in version 0.9.
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
A dict with the contents of all cookies transmitted with the request.
Contains the incoming request data as string in case it came with a mimetype Werkzeug does not handle.
The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822.
Changed in version 2.0: The datetime object is timezone-aware.
alias of werkzeug.datastructures.ImmutableMultiDict
The endpoint that matched the request. This in combination with view_args can be used to reconstruct the same or a modified URL. If an exception happened when matching, this will be None.
The WSGI environment containing HTTP headers and information from the WSGI server.
MultiDict object containing all uploaded files. Each key in files is the name from the <input type="file" name="">. Each value in files is a Werkzeug FileStorage object.
It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem.
Note that files will only contain data if the request method was POST, PUT or PATCH and the <form> that posted to the request had enctype="multipart/form-data". It will be empty otherwise.
See the MultiDict / FileStorage documentation for more details about the used data structure.
The form parameters. By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important.
Please keep in mind that file uploads will not end up here, but instead in the files attribute.
Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests.
alias of werkzeug.formparser.FormDataParser
Create a new request object based on the values provided. If environ is given missing values are filled from there. This method is useful for small scripts when you need to simulate a request from an URL. Do not use this method for unittesting, there is a full featured client object (Client) that allows to create multipart requests, support for cookies etc.
This accepts the same options as the EnvironBuilder.
Changed in version 0.5: This method now accepts the same arguments as EnvironBuilder. Because of this the environ parameter is now called environ_overrides.
request object
werkzeug.wrappers.request.Request
Requested path, including the query string.
This reads the buffered incoming data from the client into one bytes object. By default this is cached but that behavior can be changed by setting cache to False.
Usually it’s a bad idea to call this method without checking the content length first as a client could send dozens of megabytes or more to cause memory problems on the server.
Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set parse_form_data to True. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory.
If as_text is set to True the return value will be a decoded string.
New in version 0.9.
Union[bytes, str]
Parse data as JSON.
If the mimetype does not indicate JSON (application/json, see is_json()), this returns None.
If parsing fails, on_json_loading_failed() is called and its return value is used as the return value.
Optional[Any]
The headers received with the request.
The host name the request was made to, including the port if it’s non-standard. Validated with trusted_hosts.
The request URL scheme and host only.
An object containing all the etags in the If-Match header.
ETags
The parsed If-Modified-Since header as a datetime object.
Changed in version 2.0: The datetime object is timezone-aware.
An object containing all the etags in the If-None-Match header.
ETags
The parsed If-Range header.
Changed in version 2.0: IfRange.date is timezone-aware.
New in version 0.7.
The parsed If-Unmodified-Since header as a datetime object.
Changed in version 2.0: The datetime object is timezone-aware.
The WSGI input stream.
In general it’s a bad idea to use this one because you can easily read past the boundary. Use the stream instead.
Check if the mimetype indicates JSON data, either application/json or application/*+json.
boolean that is True if the application is served by a WSGI server that spawns multiple processes.
boolean that is True if the application is served by a multithreaded WSGI server.
boolean that is True if the application will be executed only once in a process lifetime. This is the case for CGI for example, but it’s not guaranteed that the execution only happens one time.
True if the request was made with a secure protocol (HTTPS or WSS).
The parsed JSON data if mimetype indicates JSON (application/json, see is_json()).
Calls get_json() with default arguments.
alias of werkzeug.datastructures.ImmutableList
Creates the form data parser. Instantiates the form_data_parser_class with some parameters.
New in version 0.8.
werkzeug.formparser.FormDataParser
Read-only view of the MAX_CONTENT_LENGTH config key.
The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server.
The method the request was made with, such as GET.
Like content_type, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type is text/HTML; charset=utf-8 the mimetype would be 'text/html'.
The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.
Called if get_json() parsing fails and isn’t silenced. If this method returns a value, it is used as the return value for get_json(). The default implementation raises BadRequest.
e (Exception) –
NoReturn
The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed.
alias of werkzeug.datastructures.ImmutableMultiDict
The path part of the URL after root_path. This is the path used for routing within the application.
The Pragma general-header field is used to include implementation-specific directives that might apply to any recipient along the request/response chain. All pragma directives specify optional behavior from the viewpoint of the protocol; however, some systems MAY require that behavior be consistent with the directives.
The part of the URL after the “?”. This is the raw value, use args for the parsed values.
The parsed Range header.
New in version 0.7.
Range
The Referer[sic] request-header field allows the client to specify, for the server’s benefit, the address (URI) of the resource from which the Request-URI was obtained (the “referrer”, although the header field is misspelled).
The address of the client sending the request.
If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.
The prefix that the application is mounted under, without a trailing slash. path comes after this.
The request URL scheme, host, and root path. This is the root that the application is accessed from.
If matching the URL failed, this is the exception that will be raised / was raised as part of the request handling. This is usually a NotFound exception or something similar.
The URL scheme of the protocol the request used, such as https or wss.
Alias for self.root_path. environ["SCRIPT_ROOT"] without a trailing slash.
The address of the server. (host, port), (path, None) for unix sockets, or None if not known.
Set when creating the request object. If True, reading from the request body will cause a RuntimeException. Useful to prevent modifying the stream from middleware.
If the incoming form data was not encoded with a known mimetype the data is stored unmodified in this stream for consumption. Most of the time it is a better idea to use data which will give you that data as a string. The stream only returns the data once.
Unlike input_stream this stream is properly guarded that you can’t accidentally read past the length of the input. Werkzeug will internally always refer to this stream to read data which makes it possible to wrap this object with a stream that does filtering.
Changed in version 0.9: This stream is now always available but might be consumed by the form parser later on. Previously the stream was only set if no parsing happened.
The full request URL with the scheme, host, root path, path, and query string.
The charset that is assumed for URLs. Defaults to the value of charset.
New in version 0.6.
Alias for root_url. The URL with scheme, host, and root path. For example, https://example.com/app/.
The internal URL rule that matched the request. This can be useful to inspect which methods are allowed for the URL from a before/after handler (request.url_rule.methods) etc. Though if the request’s method was invalid for the URL rule, the valid list is available in routing_exception.valid_methods instead (an attribute of the Werkzeug exception MethodNotAllowed) because the request was never internally bound.
New in version 0.6.
The user agent. Use user_agent.string to get the header value. Set user_agent_class to a subclass of UserAgent to provide parsing for the other properties or other extended data.
Changed in version 2.0: The built in parser is deprecated and will be removed in Werkzeug 2.1. A UserAgent subclass must be set to parse data from the string.
alias of werkzeug.useragents._UserAgent
A werkzeug.datastructures.CombinedMultiDict that combines args and form.
For GET requests, only args are present, not form.
Changed in version 2.0: For GET requests, only args are present, not form.
A dict of view arguments that matched the request. If an exception happened when matching, this will be None.
True if the request method carries content. By default this is true if a Content-Type is sent.
New in version 0.8.


Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set access_control_allow_headers on the response to indicate which headers are allowed.


Sent with a preflight request to indicate which method will be used for the cross origin request. Set access_control_allow_methods on the response to indicate which methods are allowed.


Decorate a function as responder that accepts the request as the last argument. This works like the responder() decorator but the function is passed the request object as the last argument and the request object will be closed automatically:
As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing.
f (Callable[[Request], WSGIApplication]) – the WSGI callable to decorate
a new WSGI callable
WSGIApplication


Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it.
New in version 0.9.
None


The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.
New in version 0.9.


The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)
New in version 0.9.


The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.


The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822.
Changed in version 2.0: The datetime object is timezone-aware.


The WSGI environment containing HTTP headers and information from the WSGI server.


Create a new request object based on the values provided. If environ is given missing values are filled from there. This method is useful for small scripts when you need to simulate a request from an URL. Do not use this method for unittesting, there is a full featured client object (Client) that allows to create multipart requests, support for cookies etc.
This accepts the same options as the EnvironBuilder.
Changed in version 0.5: This method now accepts the same arguments as EnvironBuilder. Because of this the environ parameter is now called environ_overrides.
request object
werkzeug.wrappers.request.Request