class documentation

class Flask(Scaffold):

View In Hierarchy

The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more.

The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an :file:`__init__.py` file inside) or a standard module (just a .py file).

For more information about resource loading, see open_resource.

Usually you create a Flask instance in your main module or in the :file:`__init__.py` file of your package like this:

from flask import Flask
app = Flask(__name__)

About the First Parameter

The idea of the first parameter is to give Flask an idea of what belongs to your application. This name is used to find resources on the filesystem, can be used by extensions to improve debugging information and a lot more.

So it's important what you provide there. If you are using a single module, __name__ is always the correct value. If you however are using a package, it's usually recommended to hardcode the name of your package there.

For example if your application is defined in :file:`yourapplication/app.py` you should create it with one of the two versions below:

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

Why is that? The application will work even with __name__, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application. For example the Flask-SQLAlchemy extension will look for the code in your application that triggered an SQL query in debug mode. If the import name is not properly set up, that debugging information is lost. (For example it would only pick up SQL queries in yourapplication.app and not yourapplication.views.frontend)

New in version 0.7: The static_url_path, static_folder, and template_folder parameters were added.
New in version 0.8: The instance_path and instance_relative_config parameters were added.
New in version 0.11: The root_path parameter was added.
New in version 1.0: The host_matching and static_host parameters were added.
New in version 1.0: The subdomain_matching parameter was added. Subdomain matching needs to be enabled manually now. Setting SERVER_NAME does not implicitly enable it.
Parameters
import​_namethe name of the application package
static​_url​_pathcan be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.
static​_folderThe folder with static files that is served at static_url_path. Relative to the application root_path or an absolute path. Defaults to 'static'.
static​_hostthe host to use when adding the static route. Defaults to None. Required when using host_matching=True with a static_folder configured.
host​_matchingset url_map.host_matching attribute. Defaults to False.
subdomain​_matchingconsider the subdomain relative to SERVER_NAME when matching routes. Defaults to False.
template​_folderthe folder that contains the templates that should be used by the application. Defaults to 'templates' folder in the root path of the application.
instance​_pathAn alternative instance path for the application. By default the folder 'instance' next to the package or module is assumed to be the instance path.
instance​_relative​_configif set to True relative filenames for loading the config are assumed to be relative to the instance path instead of the application root.
root​_pathThe path to the root of the application files. This should only be set manually when it can't be detected automatically, such as for namespace packages.
Method __call__ The WSGI server calls the Flask application object as the WSGI application. This calls wsgi_app, which can be wrapped to apply middleware.
Method __init__ Undocumented
Method ​_find​_error​_handler No summary
Method ​_is​_setup​_finished Undocumented
Method add​_template​_filter Register a custom template filter. Works exactly like the template_filter decorator.
Method add​_template​_global Register a custom template global function. Works exactly like the template_global decorator.
Method add​_template​_test Register a custom template test. Works exactly like the template_test decorator.
Method add​_url​_rule Register a rule for routing incoming requests and building URLs. The route decorator is a shortcut to call this with the view_func argument. These are equivalent:
Method app​_context Create an ~flask.ctx.AppContext. Use as a with block to push the context, which will make current_app point at this application.
Method async​_to​_sync Return a sync function that will run the coroutine function.
Method auto​_find​_instance​_path No summary
Method before​_first​_request Registers a function to be run before the first request to this instance of the application.
Method create​_global​_jinja​_loader No summary
Method create​_jinja​_environment No summary
Method create​_url​_adapter 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.
Method debug.setter Undocumented
Method dispatch​_request No summary
Method do​_teardown​_appcontext Called right before the application context is popped.
Method do​_teardown​_request Called after the request is dispatched and the response is returned, right before the request context is popped.
Method ensure​_sync 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.
Method finalize​_request No summary
Method full​_dispatch​_request Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling.
Method handle​_exception 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.
Method handle​_http​_exception Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.
Method handle​_url​_build​_error Handle ~werkzeug.routing.BuildError on url_for.
Method handle​_user​_exception No summary
Method inject​_url​_defaults Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building.
Method iter​_blueprints Iterates over all blueprints by the order they were registered.
Method log​_exception No summary
Method make​_config No summary
Method make​_default​_options​_response This method is called to create the default OPTIONS response. This can be changed through subclassing to change the default behavior of OPTIONS responses.
Method make​_response Convert the return value from a view function to an instance of response_class.
Method make​_shell​_context Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors.
Method open​_instance​_resource No summary
Method preprocess​_request No summary
Method process​_response 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.
Method raise​_routing​_exception No summary
Method register​_blueprint Register a ~flask.Blueprint on the application. Keyword arguments passed to this method will override the defaults set on the blueprint.
Method request​_context Create a ~flask.ctx.RequestContext representing a WSGI environment. Use a with block to push the context, which will make request point at this request.
Method run Runs the application on a local development server.
Method select​_jinja​_autoescape Returns True if autoescaping should be active for the given template name. If no template name is given, returns True.
Method shell​_context​_processor Registers a shell context processor function.
Method should​_ignore​_error No summary
Method teardown​_appcontext Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped.
Method template​_filter 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:
Method template​_global 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:
Method template​_test 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:
Method templates​_auto​_reload.setter Undocumented
Method test​_cli​_runner Create a CLI runner for testing CLI commands. See :ref:`testing-cli`.
Method test​_client Creates a test client for this application. For information about unit testing head over to :doc:`/testing`.
Method test​_request​_context No summary
Method trap​_http​_exception No summary
Method try​_trigger​_before​_first​_request​_functions Called before each request and will ensure that it triggers the before_first_request_funcs and only exactly once per application instance (which means process usually).
Method update​_template​_context No summary
Method wsgi​_app 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:
Class Variable default​_config Undocumented
Class Variable jinja​_options Undocumented
Class Variable permanent​_session​_lifetime Undocumented
Class Variable secret​_key Undocumented
Class Variable send​_file​_max​_age​_default Undocumented
Class Variable session​_cookie​_name Undocumented
Class Variable session​_interface Undocumented
Class Variable test​_cli​_runner​_class Undocumented
Class Variable test​_client​_class Undocumented
Class Variable testing Undocumented
Class Variable use​_x​_sendfile Undocumented
Instance Variable ​_before​_request​_lock Undocumented
Instance Variable ​_got​_first​_request Undocumented
Instance Variable before​_first​_request​_funcs Undocumented
Instance Variable blueprints Undocumented
Instance Variable config Undocumented
Instance Variable debug No summary
Instance Variable env Undocumented
Instance Variable extensions Undocumented
Instance Variable instance​_path Undocumented
Instance Variable shell​_context​_processors Undocumented
Instance Variable subdomain​_matching Undocumented
Instance Variable teardown​_appcontext​_funcs Undocumented
Instance Variable url​_build​_error​_handlers Undocumented
Instance Variable url​_map Undocumented
Property got​_first​_request This attribute is set to True if the application started handling the first request.
Property jinja​_env The Jinja environment used to load templates.
Property logger A standard Python ~logging.Logger for the app, with the same name as name.
Property name No summary
Property preserve​_context​_on​_exception Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTION configuration value in case it's set, otherwise a sensible default is returned.
Property propagate​_exceptions Returns the value of the PROPAGATE_EXCEPTIONS configuration value in case it's set, otherwise a sensible default is returned.
Property templates​_auto​_reload Reload templates when they are changed. Used by create_jinja_environment.

Inherited from Scaffold:

Static Method ​_get​_exc​_class​_and​_code Get the exception class being handled. For HTTP status codes or HTTPException subclasses, return both the exception and status code.
Method __repr__ Undocumented
Method ​_method​_route Undocumented
Method after​_request Register a function to run after each request to this object.
Method before​_request Register a function to run before each request.
Method context​_processor Registers a template context processor function.
Method delete Shortcut for route with methods=["DELETE"].
Method endpoint 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.
Method errorhandler Register a function to handle errors by code or exception class.
Method get Shortcut for route with methods=["GET"].
Method get​_send​_file​_max​_age Used by send_file to determine the max_age cache value for a given file path if it wasn't passed.
Method open​_resource Open a resource file relative to root_path for reading.
Method patch Shortcut for route with methods=["PATCH"].
Method post Shortcut for route with methods=["POST"].
Method put Shortcut for route with methods=["PUT"].
Method register​_error​_handler Alternative error attach function to the errorhandler decorator that is more straightforward to use for non decorator usage.
Method route 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.
Method send​_static​_file No summary
Method static​_folder.setter Undocumented
Method static​_url​_path.setter Undocumented
Method teardown​_request No summary
Method url​_defaults 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.
Method url​_value​_preprocessor Register a URL value preprocessor function for all view functions in the application. These functions will be called before the before_request functions.
Class Variable json​_decoder Undocumented
Class Variable json​_encoder Undocumented
Instance Variable ​_static​_folder Undocumented
Instance Variable ​_static​_url​_path Undocumented
Instance Variable after​_request​_funcs Undocumented
Instance Variable before​_request​_funcs Undocumented
Instance Variable cli Undocumented
Instance Variable error​_handler​_spec Undocumented
Instance Variable import​_name Undocumented
Instance Variable root​_path Undocumented
Instance Variable teardown​_request​_funcs Undocumented
Instance Variable template​_context​_processors Undocumented
Instance Variable template​_folder Undocumented
Instance Variable url​_default​_functions Undocumented
Instance Variable url​_value​_preprocessors Undocumented
Instance Variable view​_functions Undocumented
Property has​_static​_folder True if static_folder is set.
Property jinja​_loader The Jinja loader for this object's templates. By default this is a class jinja2.loaders.FileSystemLoader to template_folder if it is set.
Property static​_folder The absolute path to the configured static folder. None if no static folder is set.
Property static​_url​_path The URL prefix that the static route will be accessible from.
def __call__(self, environ, start_response):
The WSGI server calls the Flask application object as the WSGI application. This calls wsgi_app, which can be wrapped to apply middleware.
Parameters
environ:dictUndocumented
start​_response:t.CallableUndocumented
Returns
t.AnyUndocumented
def __init__(self, import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None):

Undocumented

Parameters
import​_name:strUndocumented
static​_url​_path:t.Optional[str]Undocumented
static​_folder:t.Optional[t.Union[str, os.PathLike]]Undocumented
static​_host:t.Optional[str]Undocumented
host​_matching:boolUndocumented
subdomain​_matching:boolUndocumented
template​_folder:t.Optional[str]Undocumented
instance​_path:t.Optional[str]Undocumented
instance​_relative​_config:boolUndocumented
root​_path:t.Optional[str]Undocumented
def _find_error_handler(self, e):
Return a registered error handler for an exception in this order: blueprint handler for a specific code, app handler for a specific code, blueprint handler for an exception class, app handler for an exception class, or None if a suitable handler is not found.
Parameters
e:ExceptionUndocumented
Returns
t.Optional[ErrorHandlerCallable[Exception]]Undocumented
def _is_setup_finished(self):

Undocumented

Returns
boolUndocumented
@setupmethod
def add_template_filter(self, f, name=None):
Register a custom template filter. Works exactly like the template_filter decorator.
Parameters
f:TemplateFilterCallableUndocumented
name:t.Optional[str]the optional name of the filter, otherwise the function name will be used.
@setupmethod
def add_template_global(self, f, name=None):

Register a custom template global function. Works exactly like the template_global decorator.

New in version 0.10.
Parameters
f:TemplateGlobalCallableUndocumented
name:t.Optional[str]the optional name of the global function, otherwise the function name will be used.
@setupmethod
def add_template_test(self, f, name=None):

Register a custom template test. Works exactly like the template_test decorator.

New in version 0.10.
Parameters
f:TemplateTestCallableUndocumented
name:t.Optional[str]the optional name of the test, otherwise the function name will be used.
@setupmethod
def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options):

Register a rule for routing incoming requests and building URLs. The route decorator is a shortcut to call this with the view_func argument. These are equivalent:

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

app.add_url_rule("/", view_func=index)

See :ref:`url-route-registrations`.

The endpoint name for the route defaults to the name of the view function if the endpoint parameter isn't passed. An error will be raised if a function has already been registered for the endpoint.

The methods parameter defaults to ["GET"]. HEAD is always added automatically, and OPTIONS is added automatically by default.

view_func does not necessarily need to be passed, but if the rule should participate in routing an endpoint name must be associated with a view function at some point with the endpoint decorator.

app.add_url_rule("/", endpoint="index")

@app.endpoint("index")
def index():
    ...

If view_func has a required_methods attribute, those methods are added to the passed and automatic methods. If it has a provide_automatic_methods attribute, it is used as the default if the parameter is not passed.

Parameters
rule:strThe URL rule string.
endpoint:t.Optional[str]The endpoint name to associate with the rule and view function. Used when routing and building URLs. Defaults to view_func.__name__.
view​_func:t.Optional[t.Callable]The view function to associate with the endpoint name.
provide​_automatic​_options:t.Optional[bool]Add the OPTIONS method and respond to OPTIONS requests automatically.
**options:t.AnyExtra options passed to the ~werkzeug.routing.Rule object.
def app_context(self):

Create an ~flask.ctx.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.

with app.app_context():
    init_db()

See :doc:`/appcontext`.

New in version 0.9.
Returns
AppContextUndocumented
def async_to_sync(self, func):

Return a sync function that will run the coroutine function.

result = app.async_to_sync(func)(*args, **kwargs)

Override this method to change how the app converts async code to be synchronously callable.

New in version 2.0.
Parameters
func:t.Callable[..., t.Coroutine]Undocumented
Returns
t.Callable[..., t.Any]Undocumented
def auto_find_instance_path(self):

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.
Returns
strUndocumented
@setupmethod
def before_first_request(self, f):

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.
Parameters
f:BeforeFirstRequestCallableUndocumented
Returns
BeforeFirstRequestCallableUndocumented
def create_global_jinja_loader(self):

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.
Returns
DispatchingJinjaLoaderUndocumented
def create_jinja_environment(self):

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.
Returns
EnvironmentUndocumented
def create_url_adapter(self, request):

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.

New in version 0.6.
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.
Changed in version 1.0: SERVER_NAME no longer implicitly enables subdomain matching. Use subdomain_matching instead.
Parameters
request:t.Optional[Request]Undocumented
Returns
t.Optional[MapAdapter]Undocumented
@debug.setter
def debug(self, value):

Undocumented

Parameters
value:boolUndocumented
def dispatch_request(self):

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.
Returns
ResponseReturnValueUndocumented
def do_teardown_appcontext(self, exc=_sentinel):

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.
Parameters
exc:t.Optional[BaseException]Undocumented
def do_teardown_request(self, exc=_sentinel):

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.

Changed in version 0.9: Added the exc argument.
Parameters
exc:t.Optional[BaseException]An unhandled exception raised while dispatching the request. Detected from the current exception information if not passed. Passed to each teardown function.
def ensure_sync(self, func):

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.
Parameters
func:t.CallableUndocumented
Returns
t.CallableUndocumented
def finalize_request(self, rv, from_error_handler=False):

Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions. This is invoked for both normal request dispatching as well as error handlers.

Because this means that it might be called as a result of a failure a special safe mode is available which can be enabled with the from_error_handler flag. If enabled, failures in response processing will be logged and otherwise ignored.

Parameters
rv:t.Union[ResponseReturnValue, HTTPException]Undocumented
from​_error​_handler:boolUndocumented
Returns
ResponseUndocumented
Unknown Field: internal
def full_dispatch_request(self):

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.
Returns
ResponseUndocumented
def handle_exception(self, e):

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 ~werkzeug.exceptions.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.
Parameters
e:ExceptionUndocumented
Returns
ResponseUndocumented
def handle_http_exception(self, e):

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 HTTPException subclasses can be handled with a catch-all handler for the base HTTPException.
New in version 0.3.
Parameters
e:HTTPExceptionUndocumented
Returns
t.Union[HTTPException, ResponseReturnValue]Undocumented
def handle_url_build_error(self, error, endpoint, values):
Handle ~werkzeug.routing.BuildError on url_for.
Parameters
error:ExceptionUndocumented
endpoint:strUndocumented
values:dictUndocumented
Returns
strUndocumented
def handle_user_exception(self, e):

This method is called whenever an exception occurs that should be handled. A special case is ~werkzeug .exceptions.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.
Parameters
e:ExceptionUndocumented
Returns
t.Union[HTTPException, ResponseReturnValue]Undocumented
def inject_url_defaults(self, endpoint, values):

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.
Parameters
endpoint:strUndocumented
values:dictUndocumented
def iter_blueprints(self):

Iterates over all blueprints by the order they were registered.

New in version 0.11.
Returns
t.ValuesView[Blueprint]Undocumented
def log_exception(self, exc_info):

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.
Parameters
exc​_info:t.Union[t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]]Undocumented
def make_config(self, instance_relative=False):

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.
Parameters
instance​_relative:boolUndocumented
Returns
ConfigUndocumented
def make_default_options_response(self):

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.
Returns
ResponseUndocumented
def make_response(self, rv):

Convert the return value from a view function to an instance of response_class.

Changed in version 0.9: Previously a tuple was interpreted as the arguments for the response object.
Parameters
rv:ResponseReturnValue

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:

str
A response object is created with the string encoded to UTF-8 as the body.
bytes
A response object is created with the bytes as the body.
dict
A dictionary that will be jsonify'd before being returned.
tuple
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.
response_class
The object is returned unchanged.
other ~werkzeug.wrappers.Response class
The object is coerced to response_class.
callable
The function is called as a WSGI application. The result is used to create a response object.
Returns
ResponseUndocumented
def make_shell_context(self):

Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors.

New in version 0.11.
Returns
dictUndocumented
def open_instance_resource(self, resource, mode='rb'):
Opens a resource from the application's instance folder (instance_path). Otherwise works like open_resource. Instance resources can also be opened for writing.
Parameters
resource:strthe name of the resource. To access resources within subfolders use forward slashes as separator.
mode:strresource file opening mode, default is 'rb'.
Returns
t.IO[t.AnyStr]Undocumented
def preprocess_request(self):

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.

Returns
t.Optional[ResponseReturnValue]Undocumented
def process_response(self, response):

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.
Parameters
response:Responsea response_class object.
Returns
Responsea new response object or the same, has to be an instance of response_class.
def raise_routing_exception(self, request):
Exceptions that are recording during routing are reraised with this method. During debug we are not reraising redirect requests for non GET, HEAD, or OPTIONS requests and we're raising a different error instead to help debug situations.
Parameters
request:RequestUndocumented
Returns
te.NoReturnUndocumented
Unknown Field: internal
@setupmethod
def register_blueprint(self, blueprint, **options):

Register a ~flask.Blueprint on the application. Keyword arguments passed to this method will override the defaults set on the blueprint.

Calls the blueprint's ~flask.Blueprint.register method after recording the blueprint in the application's blueprints.

Changed in version 2.0.1: The name option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for url_for.
New in version 0.7.
Parameters
blueprint:BlueprintThe blueprint to register.
**options:t.AnyAdditional keyword arguments are passed to ~flask.blueprints.BlueprintSetupState. They can be accessed in ~flask.Blueprint.record callbacks.
url​_prefixBlueprint routes will be prefixed with this.
subdomainBlueprint routes will match on this subdomain.
url​_defaultsBlueprint routes will use these default values for view arguments.
def request_context(self, environ):

Create a ~flask.ctx.RequestContext representing a WSGI environment. Use a with block to push the context, which will make request point at this request.

See :doc:`/reqcontext`.

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.

Parameters
environ:dicta WSGI environment
Returns
RequestContextUndocumented
def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):

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 :doc:`/deploying/index` 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 :command:`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.

Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from :file:`.env` and :file:`.flaskenv` files.

If set, the :envvar:`FLASK_ENV` and :envvar:`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.
Parameters
host:t.Optional[str]the hostname to listen on. Set this to '0.0.0.0' to have the server available externally as well. Defaults to '127.0.0.1' or the host in the SERVER_NAME config variable if present.
port:t.Optional[int]the port of the webserver. Defaults to 5000 or the port defined in the SERVER_NAME config variable if present.
debug:t.Optional[bool]if given, enable or disable debug mode. See debug.
load​_dotenv:boolLoad the nearest :file:`.env` and :file:`.flaskenv` files to set environment variables. Will also change the working directory to the directory containing the first file found.
**options:t.Anythe options to be forwarded to the underlying Werkzeug server. See werkzeug.serving.run_simple for more information.
def select_jinja_autoescape(self, filename):

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.
Parameters
filename:strUndocumented
Returns
boolUndocumented
@setupmethod
def shell_context_processor(self, f):

Registers a shell context processor function.

New in version 0.11.
Parameters
f:t.CallableUndocumented
Returns
t.CallableUndocumented
def should_ignore_error(self, error):

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.
Parameters
error:t.Optional[BaseException]Undocumented
Returns
boolUndocumented
@setupmethod
def teardown_appcontext(self, f):

Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped.

Example:

ctx = app.app_context()
ctx.push()
...
ctx.pop()

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.
Parameters
f:TeardownCallableUndocumented
Returns
TeardownCallableUndocumented
@setupmethod
def template_filter(self, name=None):

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:

@app.template_filter()
def reverse(s):
    return s[::-1]
Parameters
name:t.Optional[str]the optional name of the filter, otherwise the function name will be used.
Returns
t.Callable[[TemplateFilterCallable], TemplateFilterCallable]Undocumented
@setupmethod
def template_global(self, name=None):

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:

@app.template_global()
def double(n):
    return 2 * n
New in version 0.10.
Parameters
name:t.Optional[str]the optional name of the global function, otherwise the function name will be used.
Returns
t.Callable[[TemplateGlobalCallable], TemplateGlobalCallable]Undocumented
@setupmethod
def template_test(self, name=None):

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:

@app.template_test()
def is_prime(n):
    if n == 2:
        return True
    for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
        if n % i == 0:
            return False
    return True
New in version 0.10.
Parameters
name:t.Optional[str]the optional name of the test, otherwise the function name will be used.
Returns
t.Callable[[TemplateTestCallable], TemplateTestCallable]Undocumented
@templates_auto_reload.setter
def templates_auto_reload(self, value):

Undocumented

Parameters
value:boolUndocumented
def test_cli_runner(self, **kwargs):

Create a CLI runner for testing CLI commands. See :ref:`testing-cli`.

Returns an instance of test_cli_runner_class, by default ~flask.testing.FlaskCliRunner. The Flask app object is passed as the first argument.

New in version 1.0.
Parameters
**kwargs:t.AnyUndocumented
Returns
FlaskCliRunnerUndocumented
def test_client(self, use_cookies=True, **kwargs):

Creates a test client for this application. For information about unit testing head over to :doc:`/testing`.

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:

app.testing = True
client = app.test_client()

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:

with app.test_client() as c:
    rv = c.get('/?vodka=42')
    assert request.args['vodka'] == '42'

Additionally, you may pass optional keyword arguments that will then be passed to the application's test_client_class constructor. For example:

from flask.testing import FlaskClient

class CustomClient(FlaskClient):
    def __init__(self, *args, **kwargs):
        self._authentication = kwargs.pop("authentication")
        super(CustomClient,self).__init__( *args, **kwargs)

app.test_client_class = CustomClient
client = app.test_client(authentication='Basic ....')

See ~flask.testing.FlaskClient for more information.

Changed in version 0.4: added support for with block usage for the client.
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.11: Added **kwargs to support passing additional keyword arguments to the constructor of test_client_class.
Parameters
use​_cookies:boolUndocumented
**kwargs:t.AnyUndocumented
Returns
FlaskClientUndocumented
def test_request_context(self, *args, **kwargs):

Create a ~flask.ctx.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 :doc:`/reqcontext`.

Use a with block to push the context, which will make request point at the request for the created environment.

with test_request_context(...):
    generate_report()

When using the shell, it may be easier to push and pop the context manually to avoid indentation.

ctx = app.test_request_context(...)
ctx.push()
...
ctx.pop()

Takes the same arguments as Werkzeug's ~werkzeug.test.EnvironBuilder, with some defaults from the application. See the linked Werkzeug docs for most of the available arguments. Flask-specific behavior is listed here.

Parameters
*args:t.Anyother positional arguments passed to ~werkzeug.test.EnvironBuilder.
**kwargs:t.Anyother keyword arguments passed to ~werkzeug.test.EnvironBuilder.
pathURL path being requested.
base​_urlBase URL where the app is being served, which path is relative to. If not given, built from PREFERRED_URL_SCHEME, subdomain, SERVER_NAME, and APPLICATION_ROOT.
subdomainSubdomain name to append to SERVER_NAME.
url​_schemeScheme to use instead of PREFERRED_URL_SCHEME.
dataThe request body, either as a string or a dict of form keys and values.
jsonIf given, this is serialized as JSON and passed as data. Also defaults content_type to application/json.
Returns
RequestContextUndocumented
def trap_http_exception(self, e):

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.
Parameters
e:ExceptionUndocumented
Returns
boolUndocumented
def try_trigger_before_first_request_functions(self):
Called before each request and will ensure that it triggers the before_first_request_funcs and only exactly once per application instance (which means process usually).
Unknown Field: internal
def update_template_context(self, context):
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.
Parameters
context:dictthe context as a dictionary that is updated in place to add extra variables.
def wsgi_app(self, environ, start_response):

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:

app = MyMiddleware(app)

It's a better idea to do this instead:

app.wsgi_app = MyMiddleware(app.wsgi_app)

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 :ref:`callbacks-and-errors`.
Parameters
environ:dictA WSGI environment.
start​_response:t.CallableA callable accepting a status code, a list of headers, and an optional exception context to start the response.
Returns
t.AnyUndocumented
default_config =

Undocumented

jinja_options: dict =

Undocumented

permanent_session_lifetime =

Undocumented

secret_key =

Undocumented

send_file_max_age_default =

Undocumented

session_cookie_name =

Undocumented

session_interface =

Undocumented

test_cli_runner_class: t.Optional[t.Type[FlaskCliRunner]] =

Undocumented

test_client_class: t.Optional[t.Type[FlaskClient]] =

Undocumented

testing =

Undocumented

use_x_sendfile =

Undocumented

_before_request_lock =

Undocumented

_got_first_request: bool =

Undocumented

before_first_request_funcs: t.List[BeforeFirstRequestCallable] =

Undocumented

blueprints: t.Dict[str, Blueprint] =

Undocumented

config =

Undocumented

@property
debug =

Whether debug mode is enabled. When using flask run to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. This maps to the DEBUG config key. This is enabled when env is 'development' and is overridden by the FLASK_DEBUG environment variable. It may not behave as expected if set in code.

Do not enable debug mode when deploying in production.

Default: True if env is 'development', or False otherwise.

env =

Undocumented

extensions: dict =

Undocumented

instance_path =

Undocumented

shell_context_processors: t.List[t.Callable[[], t.Dict[str, t.Any]]] =

Undocumented

subdomain_matching =

Undocumented

teardown_appcontext_funcs: t.List[TeardownCallable] =

Undocumented

url_build_error_handlers: t.List[t.Callable[[Exception, str, dict], str]] =

Undocumented

url_map =

Undocumented

@property
got_first_request: bool =

This attribute is set to True if the application started handling the first request.

New in version 0.8.

The Jinja environment used to load templates.

The environment is created the first time this property is accessed. Changing jinja_options after that will have no effect.

@locked_cached_property
logger: logging.Logger =

A standard Python ~logging.Logger for the app, with the same name as name.

In debug mode, the logger's ~logging.Logger.level will be set to ~logging.DEBUG.

If there are no handlers configured, a default handler will be added. See :doc:`/logging` for more information.

Changed in version 1.1.0: The logger takes the same name as name rather than hard-coding "flask.app".
Changed in version 1.0.0: Behavior was simplified. The logger is always named "flask.app". The level is only set during configuration, it doesn't check app.debug each time. Only one format is used, not different ones depending on app.debug. No handlers are removed, and a handler is only added if no handlers are already configured.
New in version 0.3.
@locked_cached_property
name: str =

The name of the application. This is usually the import name with the difference that it's guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value.

New in version 0.8.
@property
preserve_context_on_exception: bool =

Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTION configuration value in case it's set, otherwise a sensible default is returned.

New in version 0.7.
@property
propagate_exceptions: bool =

Returns the value of the PROPAGATE_EXCEPTIONS configuration value in case it's set, otherwise a sensible default is returned.

New in version 0.7.
@property
templates_auto_reload: bool =

Reload templates when they are changed. Used by create_jinja_environment.

This attribute can be configured with TEMPLATES_AUTO_RELOAD. If not set, it will be enabled in debug mode.

New in version 1.0: This property was added but the underlying config and behavior already existed.