暴走的电池 · flask框架怎么建立菜单栏 - CSDN文库· 3 天前 · |
谈吐大方的铁链 · Xpath解析及其语法|flask|六狼博客 ...· 3 天前 · |
高大的桔子 · Solved: Uncaught ...· 1 月前 · |
没读研的菠萝 · 西藏在南亚大通道建设中需处理好的若干关系_西 ...· 2 月前 · |
聪明伶俐的枇杷 · 万科未来时光-西安万科未来时光楼盘详情-西安房天下· 2 月前 · |
爱旅游的牛排 · 倒排索引 - Apache Doris· 2 月前 · |
快乐的板凳 · 【张佑赫结婚】盘点张佑赫女友徐智英揭秘娱乐圈 ...· 3 月前 · |
This part of the documentation covers all the interfaces of Flask. For parts where Flask depends on external libraries, we document the most important right here and provide links to the canonical documentation.
The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more.
The name of the package is used to resolve resources from inside the
package or the folder the module is contained in depending on if the
package parameter resolves to an actual python package (a folder with
an
__init__.py
file inside) or a standard module (just a
.py
file).
For more information about resource loading, see
open_resource()
.
Usually you create a
Flask
instance in your main module or
in the
__init__.py
file of your package like this:
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 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
)
Changelog
New in version 1.0: The host_matching
and static_host
parameters were added.
New in version 1.0: The subdomain_matching
parameter was added. Subdomain
matching needs to be enabled manually now. Setting
SERVER_NAME
does not implicitly enable it.
New in version 0.11: The root_path
parameter was added.
New in version 0.8: The instance_path
and instance_relative_config
parameters were
added.
New in version 0.7: The static_url_path
, static_folder
, and template_folder
parameters were added.
Parameters:
import_name (str) – the name of the application package
static_url_path (str | None) – can be used to specify a different path for the
static files on the web. Defaults to the name
of the static_folder
folder.
static_folder (str | os.PathLike[str] | None) – The 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_host (str | None) – the host to use when adding the static route.
Defaults to None. Required when using host_matching=True
with a static_folder
configured.
host_matching (bool) – set url_map.host_matching
attribute.
Defaults to False.
subdomain_matching (bool) – consider the subdomain relative to
SERVER_NAME
when matching routes. Defaults to False.
template_folder (str | os.PathLike[str] | None) – the folder that contains the templates that should
be used by the application. Defaults to
'templates'
folder in the root path of the
application.
instance_path (str | None) – An 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_config (bool) – if set to True
relative filenames
for loading the config are assumed to
be relative to the instance path instead
of the application root.
root_path (str | None) – The 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.
session_interface: SessionInterface = <flask.sessions.SecureCookieSessionInterface object>¶
the session interface to use. By default an instance of
SecureCookieSessionInterface
is used here.
Changelog 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.
get_send_file_max_age(filename)¶
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.
Note this is a duplicate of the same method in the Flask
class.
Changelog
Changed in version 2.0: The default configuration is None
instead of 12 hours.
New in version 0.9.
Parameters:
filename (str | None) –
Return type:
int | None
send_static_file(filename)¶
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
Note this is a duplicate of the same method in the Flask
class.
Changelog
New in version 0.5.
Parameters:
filename (str) –
Return type:
open_resource(resource, mode='rb')¶
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:
with app.open_resource("schema.sql") as f:
conn.executescript(f.read())
Parameters:
resource (str) – Path to the resource relative to
root_path
.
mode (str) – Open the file in this mode. Only reading is
supported, valid values are “r” (or “rt”) and “rb”.
Return type:
Note this is a duplicate of the same method in the Flask
class.
open_instance_resource(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 (str) – the name of the resource. To access resources within
subfolders use forward slashes as separator.
mode (str) – resource file opening mode, default is ‘rb’.
Return type:
create_jinja_environment()¶
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.
Changelog
Changed in version 0.11: Environment.auto_reload
set in accordance with
TEMPLATES_AUTO_RELOAD
configuration option.
New in version 0.5.
Return type:
Environment
create_url_adapter(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.
Changelog
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.
Parameters:
request (Request | None) –
Return type:
MapAdapter | None
update_template_context(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 (dict[str, Any]) – the context as a dictionary that is updated in place
to add extra variables.
Return type:
make_shell_context()¶
Returns the shell context for an interactive shell for this
application. This runs all the registered shell context
processors.
Changelog
New in version 0.11.
Return type:
run(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 Deploying to Production 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.
Parameters:
host (str | None) – 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 (int | None) – the port of the webserver. Defaults to 5000
or the
port defined in the SERVER_NAME
config variable if present.
debug (bool | None) – if given, enable or disable debug mode. See
debug
.
load_dotenv (bool) – Load the nearest .env
and .flaskenv
files to set environment variables. Will also change the working
directory to the directory containing the first file found.
options (Any) – the options to be forwarded to the underlying Werkzeug
server. See werkzeug.serving.run_simple()
for more
information.
Return type:
Changelog
Changed in version 1.0: If installed, python-dotenv will be used to load environment
variables from .env
and .flaskenv
files.
The FLASK_DEBUG
environment variable will override debug
.
Threaded mode is enabled by default.
Changed in version 0.10: The default port is now picked from the SERVER_NAME
variable.
test_client(use_cookies=True, **kwargs)¶
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:
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 FlaskClient
for more information.
Changelog
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.
Parameters:
use_cookies (bool) –
kwargs (t.Any) –
Return type:
test_cli_runner(**kwargs)¶
Create a CLI runner for testing CLI commands.
See Running Commands with the CLI Runner.
Returns an instance of test_cli_runner_class
, by default
FlaskCliRunner
. The Flask app object is
passed as the first argument.
Changelog
New in version 1.0.
Parameters:
kwargs (t.Any) –
Return type:
handle_http_exception(e)¶
Handles an HTTP exception. By default this will invoke the
registered error handlers and fall back to returning the
exception as response.
Changelog
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 (HTTPException) –
Return type:
HTTPException | ft.ResponseReturnValue
handle_user_exception(e)¶
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.
Changelog
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 (Exception) –
Return type:
HTTPException | ft.ResponseReturnValue
handle_exception(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 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
.
Changelog
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 (Exception) –
Return type:
log_exception(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
.
Changelog
New in version 0.8.
Parameters:
exc_info (tuple[type, BaseException, TracebackType] | tuple[None, None, None]) –
Return type:
dispatch_request()¶
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()
.
Changelog
Changed in version 0.7: This no longer does the exception handling, this code was
moved to the new full_dispatch_request()
.
Return type:
ft.ResponseReturnValue
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.
Changelog
New in version 0.7.
Return type:
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.
Changelog
New in version 0.7.
Return type:
ensure_sync(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.
Changelog
New in version 2.0.
Parameters:
Return type:
async_to_sync(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.
Changelog
New in version 2.0.
Parameters:
Return type:
url_for(endpoint, *, _anchor=None, _method=None, _scheme=None, _external=None, **values)¶
Generate a URL to the given endpoint with the given values.
This is called by flask.url_for()
, and can be called
directly as well.
An endpoint is the name of a URL rule, usually added with
@app.route()
, and usually the same name as the
view function. A route defined in a Blueprint
will prepend the blueprint’s name separated by a .
to the
endpoint.
In some cases, such as email messages, you want URLs to include
the scheme and domain, like https://example.com/hello
. When
not in an active request, URLs will be external by default, but
this requires setting SERVER_NAME
so Flask knows what
domain to use. APPLICATION_ROOT
and
PREFERRED_URL_SCHEME
should also be configured as
needed. This config is only used when not in an active request.
Functions can be decorated with url_defaults()
to modify
keyword arguments before the URL is built.
If building fails for some reason, such as an unknown endpoint
or incorrect values, the app’s handle_url_build_error()
method is called. If that returns a string, that is returned,
otherwise a BuildError
is raised.
Parameters:
endpoint (str) – The endpoint name associated with the URL to
generate. If this starts with a .
, the current blueprint
name (if any) will be used.
_anchor (str | None) – If given, append this as #anchor
to the URL.
_method (str | None) – If given, generate the URL associated with this
method for the endpoint.
_scheme (str | None) – If given, the URL will have this scheme if it
is external.
_external (bool | None) – If given, prefer the URL to be internal
(False) or require it to be external (True). External URLs
include the scheme and domain. When not in an active
request, URLs are external by default.
values (Any) – Values to use for the variable parts of the URL
rule. Unknown keys are appended as query string arguments,
like ?a=b&c=d
.
Return type:
Changelog
New in version 2.2: Moved from flask.url_for
, which calls this method.
make_response(rv)¶
Convert the return value from a view function to an instance of
response_class
.
Parameters:
rv (ft.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.
list
A list that will be jsonify’d before being returned.
generator
or iterator
A generator that returns str
or bytes
to be
streamed as the response.
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 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.
Changelog
Changed in version 2.2: A generator will be converted to a streaming response.
A list will be converted to a JSON response.
Changed in version 1.1: A dict will be converted to a JSON response.
Changed in version 0.9: Previously a tuple was interpreted as the arguments for the
response object.
preprocess_request()¶
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.
Return type:
ft.ResponseReturnValue | None
process_response(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.
Changelog
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 (Response) – a response_class
object.
Returns:
a new response object or the same, has to be an
instance of response_class
.
Return type:
do_teardown_request(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.
Parameters:
exc (BaseException | None) – An unhandled exception raised while dispatching the
request. Detected from the current exception information if
not passed. Passed to each teardown function.
Return type:
Changelog
Changed in version 0.9: Added the exc
argument.
do_teardown_appcontext(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()
.
Changelog
New in version 0.9.
Parameters:
exc (BaseException | None) –
Return type:
app_context()¶
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.
with app.app_context():
init_db()
Changelog
New in version 0.9.
Return type:
request_context(environ)¶
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.
Parameters:
environ (WSGIEnvironment) – a WSGI environment
Return type:
test_request_context(*args, **kwargs)¶
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.
with app.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
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:
path – URL path being requested.
base_url – Base 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
.
subdomain – Subdomain name to append to
SERVER_NAME
.
url_scheme – Scheme to use instead of
PREFERRED_URL_SCHEME
.
data – The request body, either as a string or a dict of
form keys and values.
json – If given, this is serialized as JSON and passed as
data
. Also defaults content_type
to
application/json
.
args (Any) – other positional arguments passed to
EnvironBuilder
.
kwargs (Any) – other keyword arguments passed to
EnvironBuilder
.
Return type:
wsgi_app(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.
Changelog
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.
Parameters:
environ (WSGIEnvironment) – A WSGI environment.
start_response (StartResponse) – A callable accepting a status code,
a list of headers, and an optional exception context to
start the response.
Return type:
cabc.Iterable[bytes]
add_template_filter(f, name=None)¶
Register a custom template filter. Works exactly like the
template_filter()
decorator.
Parameters:
name (str | None) – the optional name of the filter, otherwise the
function name will be used.
Return type:
add_template_global(f, name=None)¶
Register a custom template global function. Works exactly like the
template_global()
decorator.
Changelog
New in version 0.10.
Parameters:
name (str | None) – the optional name of the global function, otherwise the
function name will be used.
Return type:
add_template_test(f, name=None)¶
Register a custom template test. Works exactly like the
template_test()
decorator.
Changelog
New in version 0.10.
Parameters:
name (str | None) – the optional name of the test, otherwise the
function name will be used.
Return type:
add_url_rule(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)
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 (str) – The URL rule string.
endpoint (str | None) – The endpoint name to associate with the rule
and view function. Used when routing and building URLs.
Defaults to view_func.__name__
.
view_func (ft.RouteCallable | None) – The view function to associate with the
endpoint name.
provide_automatic_options (bool | None) – Add the OPTIONS
method and
respond to OPTIONS
requests automatically.
options (t.Any) – Extra options passed to the
Rule
object.
Return type:
after_request(f)¶
Register a function to run after each request to this object.
The function is called with the response object, and must return
a response object. This allows the functions to modify or
replace the response before it is sent.
If a function raises an exception, any remaining
after_request
functions will not be called. Therefore, this
should not be used for actions that must execute, such as to
close resources. Use teardown_request()
for that.
This is available on both app and blueprint objects. When used on an app, this
executes after every request. When used on a blueprint, this executes after
every request that the blueprint handles. To register with a blueprint and
execute after every request, use Blueprint.after_app_request()
.
Parameters:
f (T_after_request) –
Return type:
T_after_request
auto_find_instance_path()¶
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.
Changelog
New in version 0.8.
Return type:
before_request(f)¶
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.
@app.before_request
def load_user():
if "user_id" in session:
g.user = db.session.get(session["user_id"])
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.
This is available on both app and blueprint objects. When used on an app, this
executes before every request. When used on a blueprint, this executes before
every request that the blueprint handles. To register with a blueprint and
execute before every request, use Blueprint.before_app_request()
.
Parameters:
f (T_before_request) –
Return type:
T_before_request
context_processor(f)¶
Registers a template context processor function. These functions run before
rendering a template. The keys of the returned dict are added as variables
available in the template.
This is available on both app and blueprint objects. When used on an app, this
is called for every rendered template. When used on a blueprint, this is called
for templates rendered from the blueprint’s views. To register with a blueprint
and affect every template, use Blueprint.app_context_processor()
.
Parameters:
f (T_template_context_processor) –
Return type:
T_template_context_processor
create_global_jinja_loader()¶
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.
Changelog
New in version 0.7.
Return type:
DispatchingJinjaLoader
property debug: bool¶
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. It may not behave as expected if set late.
Do not enable debug mode when deploying in production.
Default: False
endpoint(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()
.
app.add_url_rule("/ex", endpoint="example")
@app.endpoint("example")
def example():
Parameters:
endpoint (str) – The endpoint name to associate with the view
function.
Return type:
Callable[[F], F]
errorhandler(code_or_exception)¶
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:
@app.errorhandler(404)
def page_not_found(error):
return 'This page does not exist', 404
You can also register handlers for arbitrary exceptions:
@app.errorhandler(DatabaseError)
def special_exception_handler(error):
return 'Database connection failed', 500
This is available on both app and blueprint objects. When used on an app, this
can handle errors from every request. When used on a blueprint, this can handle
errors from requests that the blueprint handles. To register with a blueprint
and affect every request, use Blueprint.app_errorhandler()
.
Changelog
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.
Parameters:
code_or_exception (type[Exception] | int) – the code as integer for the handler, or
an arbitrary exception
Return type:
Callable[[T_error_handler], T_error_handler]
handle_url_build_error(error, endpoint, values)¶
Called by url_for()
if a
BuildError
was raised. If this returns
a value, it will be returned by url_for
, otherwise the error
will be re-raised.
Each function in url_build_error_handlers
is called with
error
, endpoint
and values
. If a function returns
None
or raises a BuildError
, it is skipped. Otherwise,
its return value is returned by url_for
.
Parameters:
error (BuildError) – The active BuildError
being handled.
endpoint (str) – The endpoint being built.
values (dict[str, Any]) – The keyword arguments passed to url_for
.
Return type:
inject_url_defaults(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.
Changelog
New in version 0.7.
Parameters:
endpoint (str) –
Return type:
property jinja_env: Environment¶
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.
property jinja_loader: BaseLoader | None¶
The Jinja loader for this object’s templates. By default this
is a class jinja2.loaders.FileSystemLoader
to
template_folder
if it is set.
Changelog 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.
Changelog A standard Python Logger
for the app, with
the same name as name
.
In debug mode, the logger’s level
will
be set to DEBUG
.
If there are no handlers configured, a default handler will be
added. See Logging for more information.
Changelog
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.
make_aborter()¶
Create the object to assign to aborter
. That object
is called by flask.abort()
to raise HTTP errors, and can
be called directly as well.
By default, this creates an instance of aborter_class
,
which defaults to werkzeug.exceptions.Aborter
.
Changelog
New in version 2.2.
Return type:
make_config(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.
Changelog
New in version 0.8.
Parameters:
instance_relative (bool) –
Return type:
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.
Changelog 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)
redirect(location, code=302)¶
Create a redirect response object.
This is called by flask.redirect()
, and can be called
directly as well.
Parameters:
location (str) – The URL to redirect to.
code (int) – The status code for the redirect.
Return type:
BaseResponse
Changelog
New in version 2.2: Moved from flask.redirect
, which calls this method.
register_blueprint(blueprint, **options)¶
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
.
Parameters:
blueprint (Blueprint) – The blueprint to register.
url_prefix – Blueprint routes will be prefixed with this.
subdomain – Blueprint routes will match on this subdomain.
url_defaults – Blueprint routes will use these default values for
view arguments.
options (t.Any) – Additional keyword arguments are passed to
BlueprintSetupState
. They can be
accessed in record()
callbacks.
Return type:
Changelog
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.
register_error_handler(code_or_exception, f)¶
Alternative error attach function to the errorhandler()
decorator that is more straightforward to use for non decorator
usage.
Changelog
New in version 0.7.
Parameters:
f (ft.ErrorHandlerCallable) –
Return type:
route(rule, **options)¶
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.
@app.route("/")
def index():
return "Hello, World!"
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.
Parameters:
rule (str) – The URL rule string.
Return type:
Callable[[T_route], T_route]
secret_key¶
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
.
select_jinja_autoescape(filename)¶
Returns True
if autoescaping should be active for the given
template name. If no template name is given, returns True
.
Changelog
Changed in version 2.2: Autoescaping is now enabled by default for .svg
files.
New in version 0.5.
Parameters:
filename (str) –
Return type:
should_ignore_error(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.
Changelog
New in version 0.10.
Parameters:
error (BaseException | None) –
Return type:
property static_folder: str | None¶
The absolute path to the configured static folder. None
if no static folder is set.
property static_url_path: str | None¶
The URL prefix that the static route will be accessible from.
If it was not configured during init, it is derived from
static_folder
.
teardown_appcontext(f)¶
Registers a function to be called when the application
context is popped. The application context is typically popped
after the request context for each request, at the end of CLI
commands, or after a manually pushed context ends.
with app.app_context():
When the with
block exits (or ctx.pop()
is called), the
teardown functions are called just before the app context is
made inactive. 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.
Teardown functions must avoid raising exceptions. If they
execute code that might fail they must surround that code with a
try
/except
block and log any errors.
The return values of teardown functions are ignored.
Changelog
New in version 0.9.
Parameters:
f (T_teardown) –
Return type:
T_teardown
teardown_request(f)¶
Register a function to be called when the request context is
popped. Typically this happens at the end of each request, but
contexts may be pushed manually as well during testing.
with app.test_request_context():
When the with
block exits (or ctx.pop()
is called), the
teardown functions are called just before the request context is
made inactive.
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.
Teardown functions must avoid raising exceptions. If they
execute code that might fail they must surround that code with a
try
/except
block and log any errors.
The return values of teardown functions are ignored.
This is available on both app and blueprint objects. When used on an app, this
executes after every request. When used on a blueprint, this executes after
every request that the blueprint handles. To register with a blueprint and
execute after every request, use Blueprint.teardown_app_request()
.
Parameters:
f (T_teardown) –
Return type:
T_teardown
template_filter(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 (str | None) – the optional name of the filter, otherwise the
function name will be used.
Return type:
Callable[[T_template_filter], T_template_filter]
template_global(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
Changelog
New in version 0.10.
Parameters:
name (str | None) – the optional name of the global function, otherwise the
function name will be used.
Return type:
Callable[[T_template_global], T_template_global]
template_test(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
Changelog
New in version 0.10.
Parameters:
name (str | None) – the optional name of the test, otherwise the
function name will be used.
Return type:
Callable[[T_template_test], T_template_test]
test_cli_runner_class: type[FlaskCliRunner] | None = None¶
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.
Changelog The test_client()
method creates an instance of this test
client class. Defaults to FlaskClient
.
Changelog 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
.
trap_http_exception(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.
Changelog
Changed in version 1.0: Bad request errors are not trapped by default in debug mode.
New in version 0.8.
Parameters:
e (Exception) –
Return type:
url_defaults(f)¶
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.
This is available on both app and blueprint objects. When used on an app, this
is called for every request. When used on a blueprint, this is called for
requests that the blueprint handles. To register with a blueprint and affect
every request, use Blueprint.app_url_defaults()
.
Parameters:
f (T_url_defaults) –
Return type:
T_url_defaults
url_value_preprocessor(f)¶
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.
This is available on both app and blueprint objects. When used on an app, this
is called for every request. When used on a blueprint, this is called for
requests that the blueprint handles. To register with a blueprint and affect
every request, use Blueprint.app_url_value_preprocessor()
.
Parameters:
f (T_url_value_preprocessor) –
Return type:
T_url_value_preprocessor
config¶
The configuration dictionary as Config
. This behaves
exactly like a regular dictionary but supports additional methods
to load a config from files.
aborter¶
An instance of aborter_class
created by
make_aborter()
. This is called by flask.abort()
to raise HTTP errors, and can be called directly as well.
Changelog Provides access to JSON methods. Functions in flask.json
will call methods on this provider when the application context
is active. Used for handling JSON requests and responses.
An instance of json_provider_class
. Can be customized by
changing that attribute on a subclass, or by assigning to this
attribute afterwards.
The default, DefaultJSONProvider
,
uses Python’s built-in json
library. A different provider
can use a different JSON library.
Changelog A list of functions that are called by
handle_url_build_error()
when url_for()
raises a
BuildError
. Each function is called
with error
, endpoint
and values
. If a function
returns None
or raises a BuildError
, it is skipped.
Otherwise, its return value is returned by url_for
.
Changelog 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.
Changelog A list of shell context processor functions that should be run
when a shell context is created.
Changelog 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.
Changelog 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'
.
Changelog 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:
from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter):
def to_python(self, value):
return value.split(',')
def to_url(self, values):
return ','.join(super(ListConverter, self).to_url(value)
for value in values)
app = Flask(__name__)
app.url_map.converters['list'] = ListConverter
template_folder¶
The path to the templates folder, relative to
root_path
, to add to the template loader. None
if
templates should not be added.
view_functions: dict[str, ft.RouteCallable]¶
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.
error_handler_spec: dict[ft.AppOrBlueprintKey, dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]]]¶
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.
before_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]]¶
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.
after_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]]¶
A data structure of functions to call at the end of each
request, in the format {scope: [functions]}
. The
scope
key is the name of a blueprint the functions are
active for, or None
for all requests.
To register a function, use the after_request()
decorator.
This data structure is internal. It should not be modified
directly and its format may change at any time.
teardown_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.TeardownCallable]]¶
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.
template_context_processors: dict[ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]]¶
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.
url_value_preprocessors: dict[ft.AppOrBlueprintKey, list[ft.URLValuePreprocessorCallable]]¶
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.
url_default_functions: dict[ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]]¶
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.
class flask.Blueprint(name, import_name, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None, cli_group=_sentinel)¶
Parameters:
name (str) –
import_name (str) –
static_folder (str | os.PathLike[str] | None) –
static_url_path (str | None) –
template_folder (str | os.PathLike[str] | None) –
url_prefix (str | None) –
subdomain (str | None) –
root_path (str | None) –
cli_group (str | None) –
cli: Group¶
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.
get_send_file_max_age(filename)¶
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.
Note this is a duplicate of the same method in the Flask
class.
Changelog
Changed in version 2.0: The default configuration is None
instead of 12 hours.
New in version 0.9.
Parameters:
filename (str | None) –
Return type:
int | None
send_static_file(filename)¶
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
Note this is a duplicate of the same method in the Flask
class.
Changelog
New in version 0.5.
Parameters:
filename (str) –
Return type:
open_resource(resource, mode='rb')¶
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:
with app.open_resource("schema.sql") as f:
conn.executescript(f.read())
Parameters:
resource (str) – Path to the resource relative to
root_path
.
mode (str) – Open the file in this mode. Only reading is
supported, valid values are “r” (or “rt”) and “rb”.
Return type:
Note this is a duplicate of the same method in the Flask
class.
add_app_template_filter(f, name=None)¶
Register a template filter, available in any template rendered by the
application. Works like the app_template_filter()
decorator. Equivalent to
Flask.add_template_filter()
.
Parameters:
name (str | None) – the optional name of the filter, otherwise the
function name will be used.
Return type:
add_app_template_global(f, name=None)¶
Register a template global, available in any template rendered by the
application. Works like the app_template_global()
decorator. Equivalent to
Flask.add_template_global()
.
Changelog
New in version 0.10.
Parameters:
name (str | None) – the optional name of the global, otherwise the
function name will be used.
Return type:
add_app_template_test(f, name=None)¶
Register a template test, available in any template rendered by the
application. Works like the app_template_test()
decorator. Equivalent to
Flask.add_template_test()
.
Changelog
New in version 0.10.
Parameters:
name (str | None) – the optional name of the test, otherwise the
function name will be used.
Return type:
add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options)¶
Register a URL rule with the blueprint. See Flask.add_url_rule()
for
full documentation.
The URL rule is prefixed with the blueprint’s URL prefix. The endpoint name,
used with url_for()
, is prefixed with the blueprint’s name.
Parameters:
rule (str) –
endpoint (str | None) –
view_func (ft.RouteCallable | None) –
provide_automatic_options (bool | None) –
options (t.Any) –
Return type:
after_app_request(f)¶
Like after_request()
, but after every request, not only those handled
by the blueprint. Equivalent to Flask.after_request()
.
Parameters:
f (T_after_request) –
Return type:
T_after_request
after_request(f)¶
Register a function to run after each request to this object.
The function is called with the response object, and must return
a response object. This allows the functions to modify or
replace the response before it is sent.
If a function raises an exception, any remaining
after_request
functions will not be called. Therefore, this
should not be used for actions that must execute, such as to
close resources. Use teardown_request()
for that.
This is available on both app and blueprint objects. When used on an app, this
executes after every request. When used on a blueprint, this executes after
every request that the blueprint handles. To register with a blueprint and
execute after every request, use Blueprint.after_app_request()
.
Parameters:
f (T_after_request) –
Return type:
T_after_request
app_context_processor(f)¶
Like context_processor()
, but for templates rendered by every view, not
only by the blueprint. Equivalent to Flask.context_processor()
.
Parameters:
f (T_template_context_processor) –
Return type:
T_template_context_processor
app_errorhandler(code)¶
Like errorhandler()
, but for every request, not only those handled by
the blueprint. Equivalent to Flask.errorhandler()
.
Parameters:
Return type:
Callable[[T_error_handler], T_error_handler]
app_template_filter(name=None)¶
Register a template filter, available in any template rendered by the
application. Equivalent to Flask.template_filter()
.
Parameters:
name (str | None) – the optional name of the filter, otherwise the
function name will be used.
Return type:
Callable[[T_template_filter], T_template_filter]
app_template_global(name=None)¶
Register a template global, available in any template rendered by the
application. Equivalent to Flask.template_global()
.
Changelog
New in version 0.10.
Parameters:
name (str | None) – the optional name of the global, otherwise the
function name will be used.
Return type:
Callable[[T_template_global], T_template_global]
app_template_test(name=None)¶
Register a template test, available in any template rendered by the
application. Equivalent to Flask.template_test()
.
Changelog
New in version 0.10.
Parameters:
name (str | None) – the optional name of the test, otherwise the
function name will be used.
Return type:
Callable[[T_template_test], T_template_test]
app_url_defaults(f)¶
Like url_defaults()
, but for every request, not only those handled by
the blueprint. Equivalent to Flask.url_defaults()
.
Parameters:
f (T_url_defaults) –
Return type:
T_url_defaults
app_url_value_preprocessor(f)¶
Like url_value_preprocessor()
, but for every request, not only those
handled by the blueprint. Equivalent to Flask.url_value_preprocessor()
.
Parameters:
f (T_url_value_preprocessor) –
Return type:
T_url_value_preprocessor
before_app_request(f)¶
Like before_request()
, but before every request, not only those handled
by the blueprint. Equivalent to Flask.before_request()
.
Parameters:
f (T_before_request) –
Return type:
T_before_request
before_request(f)¶
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.
@app.before_request
def load_user():
if "user_id" in session:
g.user = db.session.get(session["user_id"])
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.
This is available on both app and blueprint objects. When used on an app, this
executes before every request. When used on a blueprint, this executes before
every request that the blueprint handles. To register with a blueprint and
execute before every request, use Blueprint.before_app_request()
.
Parameters:
f (T_before_request) –
Return type:
T_before_request
context_processor(f)¶
Registers a template context processor function. These functions run before
rendering a template. The keys of the returned dict are added as variables
available in the template.
This is available on both app and blueprint objects. When used on an app, this
is called for every rendered template. When used on a blueprint, this is called
for templates rendered from the blueprint’s views. To register with a blueprint
and affect every template, use Blueprint.app_context_processor()
.
Parameters:
f (T_template_context_processor) –
Return type:
T_template_context_processor
endpoint(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()
.
app.add_url_rule("/ex", endpoint="example")
@app.endpoint("example")
def example():
Parameters:
endpoint (str) – The endpoint name to associate with the view
function.
Return type:
Callable[[F], F]
errorhandler(code_or_exception)¶
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:
@app.errorhandler(404)
def page_not_found(error):
return 'This page does not exist', 404
You can also register handlers for arbitrary exceptions:
@app.errorhandler(DatabaseError)
def special_exception_handler(error):
return 'Database connection failed', 500
This is available on both app and blueprint objects. When used on an app, this
can handle errors from every request. When used on a blueprint, this can handle
errors from requests that the blueprint handles. To register with a blueprint
and affect every request, use Blueprint.app_errorhandler()
.
Changelog
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.
Parameters:
code_or_exception (type[Exception] | int) – the code as integer for the handler, or
an arbitrary exception
Return type:
Callable[[T_error_handler], T_error_handler]
property jinja_loader: BaseLoader | None¶
The Jinja loader for this object’s templates. By default this
is a class jinja2.loaders.FileSystemLoader
to
template_folder
if it is set.
Changelog Creates an instance of BlueprintSetupState()
object that is later passed to the register callback functions.
Subclasses can override this to return a subclass of the setup state.
Parameters:
app (App) –
first_registration (bool) –
Return type:
record(func)¶
Registers a function that is called when the blueprint is
registered on the application. This function is called with the
state as argument as returned by the make_setup_state()
method.
Parameters:
func (Callable[[BlueprintSetupState], None]) –
Return type:
record_once(func)¶
Works like record()
but wraps the function in another
function that will ensure the function is only called once. If the
blueprint is registered a second time on the application, the
function passed is not called.
Parameters:
func (Callable[[BlueprintSetupState], None]) –
Return type:
register(app, options)¶
Called by Flask.register_blueprint()
to register all
views and callbacks registered on the blueprint with the
application. Creates a BlueprintSetupState
and calls
each record()
callback with it.
Parameters:
app (App) – The application this blueprint is being registered
with.
options (dict[str, t.Any]) – Keyword arguments forwarded from
register_blueprint()
.
Return type:
Changelog
Changed in version 2.3: Nested blueprints now correctly apply subdomains.
Changed in version 2.1: Registering the same blueprint with the same name multiple
times is an error.
Changed in version 2.0.1: Nested blueprints are registered with their dotted name.
This allows different blueprints with the same name to be
nested at different locations.
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
.
register_blueprint(blueprint, **options)¶
Register a Blueprint
on this blueprint. Keyword
arguments passed to this method will override the defaults set
on the blueprint.
Changelog
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 2.0.
Parameters:
blueprint (Blueprint) –
options (Any) –
Return type:
register_error_handler(code_or_exception, f)¶
Alternative error attach function to the errorhandler()
decorator that is more straightforward to use for non decorator
usage.
Changelog
New in version 0.7.
Parameters:
f (ft.ErrorHandlerCallable) –
Return type:
route(rule, **options)¶
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.
@app.route("/")
def index():
return "Hello, World!"
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.
Parameters:
rule (str) – The URL rule string.
Return type:
Callable[[T_route], T_route]
property static_folder: str | None¶
The absolute path to the configured static folder. None
if no static folder is set.
property static_url_path: str | None¶
The URL prefix that the static route will be accessible from.
If it was not configured during init, it is derived from
static_folder
.
teardown_app_request(f)¶
Like teardown_request()
, but after every request, not only those
handled by the blueprint. Equivalent to Flask.teardown_request()
.
Parameters:
f (T_teardown) –
Return type:
T_teardown
teardown_request(f)¶
Register a function to be called when the request context is
popped. Typically this happens at the end of each request, but
contexts may be pushed manually as well during testing.
with app.test_request_context():
When the with
block exits (or ctx.pop()
is called), the
teardown functions are called just before the request context is
made inactive.
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.
Teardown functions must avoid raising exceptions. If they
execute code that might fail they must surround that code with a
try
/except
block and log any errors.
The return values of teardown functions are ignored.
This is available on both app and blueprint objects. When used on an app, this
executes after every request. When used on a blueprint, this executes after
every request that the blueprint handles. To register with a blueprint and
execute after every request, use Blueprint.teardown_app_request()
.
Parameters:
f (T_teardown) –
Return type:
T_teardown
url_defaults(f)¶
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.
This is available on both app and blueprint objects. When used on an app, this
is called for every request. When used on a blueprint, this is called for
requests that the blueprint handles. To register with a blueprint and affect
every request, use Blueprint.app_url_defaults()
.
Parameters:
f (T_url_defaults) –
Return type:
T_url_defaults
url_value_preprocessor(f)¶
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.
This is available on both app and blueprint objects. When used on an app, this
is called for every request. When used on a blueprint, this is called for
requests that the blueprint handles. To register with a blueprint and affect
every request, use Blueprint.app_url_value_preprocessor()
.
Parameters:
f (T_url_value_preprocessor) –
Return type:
T_url_value_preprocessor
template_folder¶
The path to the templates folder, relative to
root_path
, to add to the template loader. None
if
templates should not be added.
view_functions: dict[str, ft.RouteCallable]¶
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.
error_handler_spec: dict[ft.AppOrBlueprintKey, dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]]]¶
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.
before_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable]]¶
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.
after_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]]]¶
A data structure of functions to call at the end of each
request, in the format {scope: [functions]}
. The
scope
key is the name of a blueprint the functions are
active for, or None
for all requests.
To register a function, use the after_request()
decorator.
This data structure is internal. It should not be modified
directly and its format may change at any time.
teardown_request_funcs: dict[ft.AppOrBlueprintKey, list[ft.TeardownCallable]]¶
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.
template_context_processors: dict[ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable]]¶
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.
url_value_preprocessors: dict[ft.AppOrBlueprintKey, list[ft.URLValuePreprocessorCallable]]¶
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.
url_default_functions: dict[ft.AppOrBlueprintKey, list[ft.URLDefaultCallable]]¶
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.
class flask.Request(environ, populate_request=True, shallow=False)¶
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.
Parameters:
environ (WSGIEnvironment) –
populate_request (bool) –
shallow (bool) –
url_rule: Rule | None = None¶
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.
Changelog A dict of view arguments that matched the request. If an exception
happened when matching, this will be None
.
routing_exception: HTTPException | None = None¶
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.
property endpoint: str | None¶
The endpoint that matched the request URL.
This will be None
if matching failed or has not been
performed yet.
This in combination with view_args
can be used to
reconstruct the same URL or a modified URL.
property blueprint: str | None¶
The registered name of the current blueprint.
This will be None
if the endpoint is not part of a
blueprint, or if URL matching failed or has not been performed
This does not necessarily match the name the blueprint was
created with. It may have been nested, or registered with a
different name.
property blueprints: list[str]¶
The registered names of the current blueprint upwards through
parent blueprints.
This will be an empty list if there is no current blueprint, or
if URL matching failed.
Changelog Called if get_json()
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
.
Parameters:
e (ValueError | None) – If parsing failed, this is the exception. It will be
None
if the content type wasn’t application/json
.
Return type:
Changelog
Changed in version 2.3: Raise a 415 error instead of 400.
property accept_encodings: Accept¶
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
.
property access_route: list[str]¶
If a forwarded header exists this is a list of all ip addresses
from the client ip to the last proxy server.
classmethod application(f)¶
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:
@Request.application
def my_wsgi_app(request):
return Response('Hello World!')
As of Werkzeug 0.14 HTTP exceptions are automatically caught and
converted to responses instead of failing.
Parameters:
f (t.Callable[[Request], WSGIApplication]) – the WSGI callable to decorate
Returns:
a new WSGI callable
Return type:
WSGIApplication
property args: MultiDict[str, str]¶
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.
Changelog
Changed in version 2.3: Invalid bytes remain percent encoded.
property authorization: Authorization | None¶
The Authorization
header parsed into an Authorization
object.
None
if the header is not present.
Changelog
Changed in version 2.3: Authorization
is no longer a dict
. The token
attribute
was added for auth schemes that use a token instead of parameters.
close()¶
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.
Changelog
New in version 0.9.
Return type:
content_encoding¶
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.
Changelog 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
content_md5¶
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.)
Changelog 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.
property cookies: ImmutableMultiDict[str, str]¶
A dict
with the contents of all cookies transmitted with
the request.
property data: bytes¶
The raw data read from stream
. Will be empty if the request
represents form data.
To get the raw data even if it represents form data, use get_data()
.
date¶
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.
Changelog
Changed in version 2.0: The datetime object is timezone-aware.
property files: ImmutableMultiDict[str, FileStorage]¶
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.
property form: ImmutableMultiDict[str, str]¶
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.
Changelog
Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST
and PUT requests.
classmethod from_values(*args, **kwargs)¶
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
.
Changelog
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
.
Returns:
request object
Parameters:
args (Any) –
kwargs (Any) –
Return type:
get_data(cache=True, as_text=False, parse_form_data=False)¶
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.
Changelog
New in version 0.9.
Parameters:
cache (bool) –
as_text (bool) –
parse_form_data (bool) –
Return type:
get_json(force=False, silent=False, cache=True)¶
Parse data
as JSON.
If the mimetype does not indicate JSON
(application/json, see is_json
), or parsing
fails, on_json_loading_failed()
is called and
its return value is used as the return value. By default this
raises a 415 Unsupported Media Type resp.
Parameters:
force (bool) – Ignore the mimetype and always try to parse JSON.
silent (bool) – Silence mimetype and parsing errors, and
return None
instead.
cache (bool) – Store the parsed JSON to return for subsequent
calls.
Return type:
Any | None
Changelog The parsed If-Modified-Since
header as a datetime object.
Changelog An object containing all the etags in the If-None-Match
header.
Return type:
property if_unmodified_since: datetime | None¶
The parsed If-Unmodified-Since
header as a datetime object.
Changelog The raw WSGI input stream, without any safety checks.
This is dangerous to use. It does not guard against infinite streams or reading
past content_length
or max_content_length
.
Use stream
instead.
is_run_once¶
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.
property json: Any | None¶
The parsed JSON data if mimetype
indicates JSON
(application/json, see is_json
).
Calls get_json()
with default arguments.
If the request content type is not application/json
, this
will raise a 415 Unsupported Media Type error.
Changelog
Changed in version 2.3: Raise a 415 error instead of 400.
Changed in version 2.1: Raise a 400 error if the content type is incorrect.
make_form_data_parser()¶
Creates the form data parser. Instantiates the
form_data_parser_class
with some parameters.
Changelog
New in version 0.8.
Return type:
max_form_memory_size: int | None = None¶
the maximum form field size. This is forwarded to the form data
parsing function (parse_form_data()
). When set and the
form
or files
attribute is accessed and the
data in memory for post data is longer than the specified value a
RequestEntityTooLarge
exception is raised.
Changelog The maximum number of multipart parts to parse, passed to
form_data_parser_class
. Parsing form data with more than this
many parts will raise RequestEntityTooLarge
.
Changelog 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.
property mimetype: str¶
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'
.
property mimetype_params: dict[str, str]¶
The mimetype parameters as dict. For example if the content
type is text/html; charset=utf-8
the params would be
{'charset': 'utf-8'}
.
property pragma: HeaderSet¶
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.
referrer¶
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).
remote_user¶
If the server supports user authentication, and the
script is protected, this attribute contains the username the
user has authenticated as.
property stream: IO[bytes]¶
The WSGI input stream, with safety checks. This stream can only be consumed
once.
Use get_data()
to get the full data as bytes or text. The data
attribute will contain the full bytes only if they do not represent form data.
The form
attribute will contain the parsed form data in that case.
Unlike input_stream
, this stream guards against infinite streams or
reading past content_length
or max_content_length
.
If max_content_length
is set, it can be enforced on streams if
wsgi.input_terminated
is set. Otherwise, an empty stream is returned.
If the limit is reached before the underlying stream is exhausted (such as a
file that is too large, or an infinite stream), the remaining contents of the
stream cannot be read safely. Depending on how the server handles this, clients
may show a “connection reset” failure instead of seeing the 413 response.
Changelog Valid host names when handling requests. By default all hosts are
trusted, which means that whatever the client says the host is
will be accepted.
Because Host
and X-Forwarded-Host
headers can be set to
any value by a malicious client, it is recommended to either set
this property or implement similar validation in the proxy (if
the application is being run behind one).
Changelog 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.
Changelog
Changed in version 2.1: The built-in parser was removed. Set user_agent_class
to a UserAgent
subclass to parse data from the string.
property values: CombinedMultiDict[str, str]¶
A werkzeug.datastructures.CombinedMultiDict
that
combines args
and form
.
For GET requests, only args
are present, not form
.
Changelog True
if the request method carries content. By default
this is true if a Content-Type
is sent.
Changelog The WSGI environment containing HTTP headers and information from
the WSGI server.
shallow: bool¶
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.
flask.request¶
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
.
class flask.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)¶
The response object that is used by default in Flask. Works like the
response object from Werkzeug but is set to have an HTML mimetype by
default. Quite often you don’t have to create this object yourself because
make_response()
will take care of that for you.
If you want to replace the response object used you can subclass this and
set response_class
to your subclass.
Changelog
Changed in version 1.0: JSON support is added to the response, like the request. This is useful
when testing to get the test client response data as JSON.
Changed in version 1.0: Added max_cookie_size
.
Parameters:
headers (Headers) –
mimetype (str | None) –
content_type (str | None) –
direct_passthrough (bool) –
autocorrect_location_header = False¶
If a redirect Location
header is a relative URL, make it an
absolute URL, including scheme and domain.
Changelog Read-only view of the MAX_COOKIE_SIZE
config key.
See max_cookie_size
in
Werkzeug’s docs.
accept_ranges¶
The Accept-Ranges
header. Even though the name would
indicate that multiple values are supported, it must be one
string token only.
The values 'bytes'
and 'none'
are common.
Changelog Whether credentials can be shared by the browser to
JavaScript code. As part of the preflight request it indicates
whether credentials can be used on the cross origin request.
add_etag(overwrite=False, weak=False)¶
Add an etag for the current response if there is none yet.
Changelog
Changed in version 2.0: SHA-1 is used to generate the value. MD5 may not be
available in some environments.
Parameters:
overwrite (bool) –
weak (bool) –
Return type:
age¶
The Age response-header field conveys the sender’s
estimate of the amount of time since the response (or its
revalidation) was generated at the origin server.
Age values are non-negative decimal integers, representing time
in seconds.
property allow: HeaderSet¶
The Allow entity-header field lists the set of methods
supported by the resource identified by the Request-URI. The
purpose of this field is strictly to inform the recipient of
valid methods associated with the resource. An Allow header
field MUST be present in a 405 (Method Not Allowed)
response.
automatically_set_content_length = True¶
Should this response object automatically set the content-length
header if possible? This is true by default.
Changelog The Cache-Control general-header field is used to specify
directives that MUST be obeyed by all caching mechanisms along the
request/response chain.
call_on_close(func)¶
Adds a function to the internal list of functions that should
be called as part of closing down the response. Since 0.7 this
function also returns the function that was passed so that this
can be used as a decorator.
Changelog
New in version 0.6.
Parameters:
Return type:
close()¶
Close the wrapped response if possible. You can also use the object
in a with statement which will automatically close it.
Changelog
New in version 0.9: Can now be used in a with statement.
Return type:
content_encoding¶
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.
property content_language: HeaderSet¶
The Content-Language entity-header field describes the
natural language(s) of the intended audience for the enclosed
entity. Note that this might not be equivalent to all the
languages used within the entity-body.
content_length¶
The Content-Length entity-header field indicates the size
of the entity-body, in decimal number of OCTETs, sent to the
recipient or, in the case of the HEAD method, the size of the
entity-body that would have been sent had the request been a
content_location¶
The Content-Location entity-header field MAY be used to
supply the resource location for the entity enclosed in the
message when that entity is accessible from a location separate
from the requested resource’s URI.
content_md5¶
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.)
property content_range: ContentRange¶
The Content-Range
header as a
ContentRange
object. Available
even if the header is not set.
Changelog The Content-Security-Policy
header as a
ContentSecurityPolicy
object. Available
even if the header is not set.
The Content-Security-Policy header adds an additional layer of
security to help detect and mitigate certain types of attacks.
property content_security_policy_report_only: ContentSecurityPolicy¶
The Content-Security-policy-report-only
header as a
ContentSecurityPolicy
object. Available
even if the header is not set.
The Content-Security-Policy-Report-Only header adds a csp policy
that is not enforced but is reported thereby helping detect
certain types of attacks.
content_type¶
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.
cross_origin_embedder_policy¶
Prevents a document from loading any cross-origin resources that do not
explicitly grant the document permission. Values must be a member of the
werkzeug.http.COEP
enum.
cross_origin_opener_policy¶
Allows control over sharing of browsing context group with cross-origin
documents. Values must be a member of the werkzeug.http.COOP
enum.
date¶
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.
Changelog
Changed in version 2.0: The datetime object is timezone-aware.
delete_cookie(key, path='/', domain=None, secure=False, httponly=False, samesite=None)¶
Delete a cookie. Fails silently if key doesn’t exist.
Parameters:
key (str) – the key (name) of the cookie to be deleted.
path (str | None) – if the cookie that should be deleted was limited to a
path, the path has to be defined here.
domain (str | None) – if the cookie that should be deleted was limited to a
domain, that domain has to be defined here.
secure (bool) – If True
, the cookie will only be available
via HTTPS.
httponly (bool) – Disallow JavaScript access to the cookie.
samesite (str | None) – Limit the scope of the cookie to only be
attached to requests that are “same-site”.
Return type:
expires¶
The Expires entity-header field gives the date/time after
which the response is considered stale. A stale cache entry may
not normally be returned by a cache.
Changelog
Changed in version 2.0: The datetime object is timezone-aware.
classmethod force_type(response, environ=None)¶
Enforce that the WSGI response is a response object of the current
type. Werkzeug will use the Response
internally in many
situations like the exceptions. If you call get_response()
on an
exception you will get back a regular Response
object, even
if you are using a custom subclass.
This method can enforce a given response type, and it will also
convert arbitrary WSGI callables into response objects if an environ
is provided:
# convert a Werkzeug response object into an instance of the
# MyResponseClass subclass.
response = MyResponseClass.force_type(response)
# convert any WSGI application into a response object
response = MyResponseClass.force_type(response, environ)
This is especially useful if you want to post-process responses in
the main dispatcher and use functionality provided by your subclass.
Keep in mind that this will modify response objects in place if
possible!
Parameters:
response (Response) – a response object or wsgi application.
environ (WSGIEnvironment | None) – a WSGI environment object.
Returns:
a response object.
Return type:
Buffer the response into a list, ignoring
implicity_sequence_conversion
and
direct_passthrough
.
Set the Content-Length
header.
Generate an ETag
header if one is not already set.
Changelog
Changed in version 2.1: Removed the no_etag
parameter.
Changed in version 2.0: An ETag
header is always added.
Changed in version 0.6: The Content-Length
header is set.
Return type:
classmethod from_app(app, environ, buffered=False)¶
Create a new response object from an application output. This
works best if you pass it an application that returns a generator all
the time. Sometimes applications may use the write()
callable
returned by the start_response
function. This tries to resolve such
edge cases automatically. But if you don’t get the expected output
you should set buffered
to True
which enforces buffering.
Parameters:
app (WSGIApplication) – the WSGI application to execute.
environ (WSGIEnvironment) – the WSGI environment to execute against.
buffered (bool) – set to True
to enforce buffering.
Returns:
a response object.
Return type:
get_app_iter(environ)¶
Returns the application iterator for the given environ. Depending
on the request method and the current status code the return value
might be an empty response rather than the one from the response.
If the request method is HEAD
or the status code is in a range
where the HTTP specification requires an empty response, an empty
iterable is returned.
Changelog
New in version 0.6.
Parameters:
environ (WSGIEnvironment) – the WSGI environment of the request.
Returns:
a response iterable.
Return type:
t.Iterable[bytes]
get_data(as_text=False)¶
The string representation of the response body. Whenever you call
this property the response iterable is encoded and flattened. This
can lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting
implicit_sequence_conversion
to False
.
If as_text
is set to True
the return value will be a decoded
string.
Changelog
New in version 0.9.
Parameters:
as_text (bool) –
Return type:
get_etag()¶
Return a tuple in the form (etag, is_weak)
. If there is no
ETag the return value is (None, None)
.
Return type:
tuple[str, bool] | tuple[None, None]
get_json(force=False, silent=False)¶
Parse data
as JSON. Useful during testing.
If the mimetype does not indicate JSON
(application/json, see is_json
), this
returns None
.
Unlike Request.get_json()
, the result is not cached.
Parameters:
force (bool) – Ignore the mimetype and always try to parse JSON.
silent (bool) – Silence parsing errors and return None
instead.
Return type:
Any | None
get_wsgi_headers(environ)¶
This is automatically called right before the response is started
and returns headers modified for the given environment. It returns a
copy of the headers from the response with some modifications applied
if necessary.
For example the location header (if present) is joined with the root
URL of the environment. Also the content length is automatically set
to zero here for certain status codes.
Changelog
Changed in version 0.6: Previously that function was called fix_headers
and modified
the response object in place. Also since 0.6, IRIs in location
and content-location headers are handled properly.
Also starting with 0.6, Werkzeug will attempt to set the content
length if it is able to figure it out on its own. This is the
case if all the strings in the response iterable are already
encoded and the iterable is buffered.
Parameters:
environ (WSGIEnvironment) – the WSGI environment of the request.
Returns:
returns a new Headers
object.
Return type:
Headers
get_wsgi_response(environ)¶
Returns the final WSGI response as tuple. The first item in
the tuple is the application iterator, the second the status and
the third the list of headers. The response returned is created
specially for the given environment. For example if the request
method in the WSGI environment is 'HEAD'
the response will
be empty and only the headers and status code will be present.
Changelog
New in version 0.6.
Parameters:
environ (WSGIEnvironment) – the WSGI environment of the request.
Returns:
an (app_iter, status, headers)
tuple.
Return type:
tuple[t.Iterable[bytes], str, list[tuple[str, str]]]
implicit_sequence_conversion = True¶
if set to False
accessing properties on the response object will
not try to consume the response iterator and convert it into a list.
Changelog If the iterator is buffered, this property will be True
. A
response object will consider an iterator to be buffered if the
response attribute is a list or tuple.
Changelog If the response is streamed (the response is not an iterable with
a length information) this property is True
. In this case streamed
means that there is no information about the number of iterations.
This is usually True
if a generator is passed to the response object.
This is useful for checking before applying some sort of post
filtering that should not take place for streamed responses.
iter_encoded()¶
Iter the response encoded with the encoding of the response.
If the response object is invoked as WSGI application the return
value of this method is used as application iterator unless
direct_passthrough
was activated.
Return type:
property json: Any | None¶
The parsed JSON data if mimetype
indicates JSON
(application/json, see is_json
).
Calls get_json()
with default arguments.
last_modified¶
The Last-Modified entity-header field indicates the date
and time at which the origin server believes the variant was
last modified.
Changelog The Location response-header field is used to redirect
the recipient to a location other than the Request-URI for
completion of the request or identification of a new
resource.
make_conditional(request_or_environ, accept_ranges=False, complete_length=None)¶
Make the response conditional to the request. This method works
best if an etag was defined for the response already. The add_etag
method can be used to do that. If called without etag just the date
header is set.
This does nothing if the request method in the request or environ is
anything but GET or HEAD.
For optimal performance when handling range requests, it’s recommended
that your response data object implements seekable
, seek
and tell
methods as described by io.IOBase
. Objects returned by
wrap_file()
automatically implement those methods.
It does not remove the body of the response because that’s something
the __call__()
function does for us automatically.
Returns self so that you can do return resp.make_conditional(req)
but modifies the object in-place.
Parameters:
request_or_environ (WSGIEnvironment | Request) – a request object or WSGI environment to be
used to make the response conditional
against.
accept_ranges (bool | str) – This parameter dictates the value of
Accept-Ranges
header. If False
(default),
the header is not set. If True
, it will be set
to "bytes"
. If it’s a string, it will use this
value.
complete_length (int | None) – Will be used only in valid Range Requests.
It will set Content-Range
complete length
value and compute Content-Length
real value.
This parameter is mandatory for successful
Range Requests completion.
Raises:
RequestedRangeNotSatisfiable
if Range
header could not be parsed or satisfied.
Return type:
Changelog
Changed in version 2.0: Range processing is skipped if length is 0 instead of
raising a 416 Range Not Satisfiable error.
make_sequence()¶
Converts the response iterator in a list. By default this happens
automatically if required. If implicit_sequence_conversion
is
disabled, this method is not automatically called and some properties
might raise exceptions. This also encodes all the items.
Changelog
New in version 0.6.
Return type:
property mimetype_params: dict[str, str]¶
The mimetype parameters as dict. For example if the
content type is text/html; charset=utf-8
the params would be
{'charset': 'utf-8'}
.
Changelog The Retry-After response-header field can be used with a
503 (Service Unavailable) response to indicate how long the
service is expected to be unavailable to the requesting client.
Time in seconds until expiration or date.
Changelog
Changed in version 2.0: The datetime object is timezone-aware.
set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)¶
Sets a cookie.
A warning is raised if the size of the cookie header exceeds
max_cookie_size
, but the header will still be set.
Parameters:
key (str) – the key (name) of the cookie to be set.
value (str) – the value of the cookie.
max_age (timedelta | int | None) – should be a number of seconds, or None
(default) if
the cookie should last only as long as the client’s
browser session.
expires (str | datetime | int | float | None) – should be a datetime
object or UNIX timestamp.
path (str | None) – limits the cookie to a given path, per default it will
span the whole domain.
domain (str | None) – if you want to set a cross-domain cookie. For example,
domain="example.com"
will set a cookie that is
readable by the domain www.example.com
,
foo.example.com
etc. Otherwise, a cookie will only
be readable by the domain that set it.
secure (bool) – If True
, the cookie will only be available
via HTTPS.
httponly (bool) – Disallow JavaScript access to the cookie.
samesite (str | None) – Limit the scope of the cookie to only be
attached to requests that are “same-site”.
Return type:
set_data(value)¶
Sets a new string as response. The value must be a string or
bytes. If a string is set it’s encoded to the charset of the
response (utf-8 by default).
Changelog
New in version 0.9.
Parameters:
Return type:
set_etag(etag, weak=False)¶
Set the etag, and override the old one if there was one.
Parameters:
etag (str) –
weak (bool) –
Return type:
property vary: HeaderSet¶
The Vary field value indicates the set of request-header
fields that fully determines, while the response is fresh,
whether a cache is permitted to use the response to reply to a
subsequent request without revalidation.
property www_authenticate: WWWAuthenticate¶
The WWW-Authenticate
header parsed into a WWWAuthenticate
object. Modifying the object will modify the header value.
This header is not set by default. To set this header, assign an instance of
WWWAuthenticate
to this attribute.
response.www_authenticate = WWWAuthenticate(
"basic", {"realm": "Authentication Required"}
Multiple values for this header can be sent to give the client multiple options.
Assign a list to set multiple headers. However, modifying the items in the list
will not automatically update the header values, and accessing this attribute
will only ever return the first value.
To unset this header, assign None
or use del
.
Changelog
Changed in version 2.3: This attribute can be assigned to to set the header. A list can be assigned
to set multiple header values. Use del
to unset the header.
Changed in version 2.3: WWWAuthenticate
is no longer a dict
. The token
attribute
was added for auth challenges that use a token instead of parameters.
response: t.Iterable[str] | t.Iterable[bytes]¶
The response body to send as the WSGI iterable. A list of strings
or bytes represents a fixed-length response, any other iterable
is a streaming response. Strings are encoded to bytes as UTF-8.
Do not set to a plain string or bytes, that will cause sending
the response to be very inefficient as it will iterate one byte
at a time.
direct_passthrough¶
Pass the response body directly through as the WSGI iterable.
This can be used when the body is a binary file or other
iterator of bytes, to skip some unnecessary checks. Use
send_file()
instead of setting this
manually.
Sessions¶
If you have set Flask.secret_key
(or configured it from
SECRET_KEY
) you can use sessions in Flask applications. A session makes
it possible to remember information from one request to another. The way Flask
does this is by using a signed cookie. The user can look at the session
contents, but can’t modify it unless they know the secret key, so make sure to
set that to something complex and unguessable.
To access the current session you can use the session
object:
class flask.session¶
The session object works pretty much like an ordinary dict, with the
difference that it keeps track of modifications.
This is a proxy. See Notes On Proxies for more information.
The following attributes are interesting:
new¶
True
if the session is new, False
otherwise.
modified¶
True
if the session object detected a modification. Be advised
that modifications on mutable structures are not picked up
automatically, in that situation you have to explicitly set the
attribute to True
yourself. Here an example:
# this change is not picked up because a mutable object (here
# a list) is changed.
session['objects'].append(42)
# so mark it as modified yourself
session.modified = True
If set to True
the session lives for
permanent_session_lifetime
seconds. The
default is 31 days. If set to False
(which is the default) the
session will be deleted when the user closes the browser.
The session interface provides a simple way to replace the session
implementation that Flask is using.
class flask.sessions.SessionInterface¶
The basic interface you have to implement in order to replace the
default session interface which uses werkzeug’s securecookie
implementation. The only methods you have to implement are
open_session()
and save_session()
, the others have
useful defaults which you don’t need to change.
The session object returned by the open_session()
method has to
provide a dictionary like interface plus the properties and methods
from the SessionMixin
. We recommend just subclassing a dict
and adding that mixin:
class Session(dict, SessionMixin):
If open_session()
returns None
Flask will call into
make_null_session()
to create a session that acts as replacement
if the session support cannot work because some requirement is not
fulfilled. The default NullSession
class that is created
will complain that the secret key was not set.
To replace the session interface on an application all you have to do
is to assign flask.Flask.session_interface
:
app = Flask(__name__)
app.session_interface = MySessionInterface()
Multiple requests with the same session may be sent and handled
concurrently. When implementing a new session interface, consider
whether reads or writes to the backing store must be synchronized.
There is no guarantee on the order in which the session for each
request is opened or saved, it will occur in the order that requests
begin and end processing.
Changelog
New in version 0.8.
null_session_class¶
make_null_session()
will look here for the class that should
be created when a null session is requested. Likewise the
is_null_session()
method will perform a typecheck against
this type.
alias of NullSession
pickle_based = False¶
A flag that indicates if the session interface is pickle based.
This can be used by Flask extensions to make a decision in regards
to how to deal with the session object.
Changelog Creates a null session which acts as a replacement object if the
real session support could not be loaded due to a configuration
error. This mainly aids the user experience because the job of the
null session is to still support lookup without complaining but
modifications are answered with a helpful error message of what
failed.
This creates an instance of null_session_class
by default.
Parameters:
app (Flask) –
Return type:
is_null_session(obj)¶
Checks if a given object is a null session. Null sessions are
not asked to be saved.
This checks if the object is an instance of null_session_class
by default.
Parameters:
obj (object) –
Return type:
get_cookie_name(app)¶
The name of the session cookie. Uses``app.config[“SESSION_COOKIE_NAME”]``.
Parameters:
app (Flask) –
Return type:
get_cookie_domain(app)¶
The value of the Domain
parameter on the session cookie. If not set,
browsers will only send the cookie to the exact domain it was set from.
Otherwise, they will send it to any subdomain of the given value as well.
Uses the SESSION_COOKIE_DOMAIN
config.
Changelog
Changed in version 2.3: Not set by default, does not fall back to SERVER_NAME
.
Parameters:
app (Flask) –
Return type:
str | None
get_cookie_path(app)¶
Returns the path for which the cookie should be valid. The
default implementation uses the value from the SESSION_COOKIE_PATH
config var if it’s set, and falls back to APPLICATION_ROOT
or
uses /
if it’s None
.
Parameters:
app (Flask) –
Return type:
get_cookie_httponly(app)¶
Returns True if the session cookie should be httponly. This
currently just returns the value of the SESSION_COOKIE_HTTPONLY
config var.
Parameters:
app (Flask) –
Return type:
get_cookie_secure(app)¶
Returns True if the cookie should be secure. This currently
just returns the value of the SESSION_COOKIE_SECURE
setting.
Parameters:
app (Flask) –
Return type:
get_cookie_samesite(app)¶
Return 'Strict'
or 'Lax'
if the cookie should use the
SameSite
attribute. This currently just returns the value of
the SESSION_COOKIE_SAMESITE
setting.
Parameters:
app (Flask) –
Return type:
str | None
get_expiration_time(app, session)¶
A helper method that returns an expiration date for the session
or None
if the session is linked to the browser session. The
default implementation returns now + the permanent session
lifetime configured on the application.
Parameters:
app (Flask) –
session (SessionMixin) –
Return type:
datetime | None
should_set_cookie(app, session)¶
Used by session backends to determine if a Set-Cookie
header
should be set for this session cookie for this response. If the session
has been modified, the cookie is set. If the session is permanent and
the SESSION_REFRESH_EACH_REQUEST
config is true, the cookie is
always set.
This check is usually skipped if the session was deleted.
Changelog
New in version 0.11.
Parameters:
app (Flask) –
session (SessionMixin) –
Return type:
open_session(app, request)¶
This is called at the beginning of each request, after
pushing the request context, before matching the URL.
This must return an object which implements a dictionary-like
interface as well as the SessionMixin
interface.
This will return None
to indicate that loading failed in
some way that is not immediately an error. The request
context will fall back to using make_null_session()
in this case.
Parameters:
app (Flask) –
request (Request) –
Return type:
SessionMixin | None
save_session(app, session, response)¶
This is called at the end of each request, after generating
a response, before removing the request context. It is skipped
if is_null_session()
returns True
.
Parameters:
app (Flask) –
session (SessionMixin) –
response (Response) –
Return type:
class flask.sessions.SecureCookieSessionInterface¶
The default session interface that stores sessions in signed cookies
through the itsdangerous
module.
salt = 'cookie-session'¶
the salt that should be applied on top of the secret key for the
signing of cookie based sessions.
static digest_method(string=b'')¶
the hash function to use for the signature. The default is sha1
Parameters:
string (bytes) –
Return type:
key_derivation = 'hmac'¶
the name of the itsdangerous supported key derivation. The default
is hmac.
serializer = <flask.json.tag.TaggedJSONSerializer object>¶
A python serializer for the payload. The default is a compact
JSON derived serializer with support for some extra Python types
such as datetime objects or tuples.
open_session(app, request)¶
This is called at the beginning of each request, after
pushing the request context, before matching the URL.
This must return an object which implements a dictionary-like
interface as well as the SessionMixin
interface.
This will return None
to indicate that loading failed in
some way that is not immediately an error. The request
context will fall back to using make_null_session()
in this case.
Parameters:
app (Flask) –
request (Request) –
Return type:
SecureCookieSession | None
save_session(app, session, response)¶
This is called at the end of each request, after generating
a response, before removing the request context. It is skipped
if is_null_session()
returns True
.
Parameters:
app (Flask) –
session (SessionMixin) –
response (Response) –
Return type:
class flask.sessions.SecureCookieSession(initial=None)¶
Base class for sessions based on signed cookies.
This session backend will set the modified
and
accessed
attributes. It cannot reliably track whether a
session is new (vs. empty), so new
remains hard coded to
False
.
Parameters:
initial (t.Any) –
modified = False¶
When data is changed, this is set to True
. Only the session
dictionary itself is tracked; if the session contains mutable
data (for example a nested dict) then this must be set to
True
manually when modifying that data. The session cookie
will only be written to the response if this is True
.
get(key, default=None)¶
Return the value for key if key is in the dictionary, else default.
Parameters:
key (str) –
default (Any) –
Return type:
setdefault(key, default=None)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
Parameters:
key (str) –
default (Any) –
Return type:
class flask.sessions.NullSession(initial=None)¶
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.
Parameters:
initial (t.Any) –
pop(k[, d]) → v, remove specified key and return the corresponding value.¶
If the key is not found, return the default if given; otherwise,
raise a KeyError.
Parameters:
args (Any) –
kwargs (Any) –
Return type:
popitem(*args, **kwargs)¶
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order.
Raises KeyError if the dict is empty.
Parameters:
args (Any) –
kwargs (Any) –
Return type:
update([E, ]**F) → None. Update D from dict/iterable E and F.¶
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
Parameters:
args (Any) –
kwargs (Any) –
Return type:
setdefault(*args, **kwargs)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
Parameters:
args (Any) –
kwargs (Any) –
Return type:
modified = True¶
Some implementations can detect changes to the session and set
this when that happens. The mixin default is hard coded to
True
.
accessed = True¶
Some implementations can detect when session data is read or
written and set this when that happens. The mixin default is hard
coded to True
.
Notice
The PERMANENT_SESSION_LIFETIME
config can be an integer or timedelta
.
The permanent_session_lifetime
attribute is always a
timedelta
.
Test Client¶
class flask.testing.FlaskClient(*args, **kwargs)¶
Works like a regular Werkzeug test client but has knowledge about
Flask’s contexts to defer the cleanup of the request context until
the end of a with
block. For general information about how to
use this class refer to werkzeug.test.Client
.
Changelog
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.
Parameters:
args (t.Any) –
kwargs (t.Any) –
session_transaction(*args, **kwargs)¶
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.
with client.session_transaction() as session:
session['value'] = 42
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.
Parameters:
args (Any) –
kwargs (Any) –
Return type:
open(*args, buffered=False, follow_redirects=False, **kwargs)¶
Generate an environ dict from the given arguments, make a
request to the application using it, and return the response.
Parameters:
args (t.Any) – Passed to EnvironBuilder
to create the
environ for the request. If a single arg is passed, it can
be an existing EnvironBuilder
or an environ dict.
buffered (bool) – Convert the iterator returned by the app into
a list. If the iterator has a close()
method, it is
called automatically.
follow_redirects (bool) – Make additional requests to follow HTTP
redirects until a non-redirect status is returned.
TestResponse.history
lists the intermediate
responses.
kwargs (t.Any) –
Return type:
TestResponse
Changelog
Changed in version 2.1: Removed the as_tuple
parameter.
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.
class flask.testing.FlaskCliRunner(app, **kwargs)¶
A CliRunner
for testing a Flask app’s
CLI commands. Typically created using
test_cli_runner()
. See Running Commands with the CLI Runner.
Parameters:
app (Flask) –
kwargs (t.Any) –
invoke(cli=None, args=None, **kwargs)¶
Invokes a CLI command in an isolated environment. See
CliRunner.invoke
for
full method documentation. See Running Commands with the CLI Runner for examples.
If the obj
argument is not given, passes an instance of
ScriptInfo
that knows how to load the Flask
app being tested.
Parameters:
cli (Any) – Command object to invoke. Default is the app’s
cli
group.
args (Any) – List of strings to invoke the command with.
kwargs (Any) –
Returns:
a Result
object.
Return type:
Application Globals¶
To share data that is valid for one request only from one function to
another, a global variable is not good enough because it would break in
threaded environments. Flask provides you with a special object that
ensures it is only valid for the active request and that will return
different values for each request. In a nutshell: it does the right
thing, like it does for request
and session
.
flask.g¶
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. For
example, a before_request
function could load a user object from
a session id, then set g.user
to be used in the view function.
This is a proxy. See Notes On Proxies for more information.
Changelog
Changed in version 0.10: Bound to the application context instead of the request context.
class flask.ctx._AppCtxGlobals¶
A plain object. Used as a namespace for storing data during an
application context.
Creating an app context automatically creates this object, which is
made available as the g
proxy.
'key' in g
Check whether an attribute is present.
Changelog Get an attribute by name, or a default value. Like
dict.get()
.
Parameters:
name (str) – Name of attribute to get.
default (Any | None) – Value to return if the attribute is not present.
Return type:
Changelog
New in version 0.10.
pop(name, default=_sentinel)¶
Get and remove an attribute by name. Like dict.pop()
.
Parameters:
name (str) – Name of attribute to pop.
default (Any) – Value to return if the attribute is not present,
instead of raising a KeyError
.
Return type:
Changelog
New in version 0.11.
setdefault(name, default=None)¶
Get the value of an attribute if it is present, otherwise
set and return a default value. Like dict.setdefault()
.
Parameters:
name (str) – Name of attribute to get.
default (Any) – Value to set and return if the attribute is not
present.
Return type:
Changelog
New in version 0.11.
flask.current_app¶
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.
flask.has_request_context()¶
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.
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and has_request_context():
remote_addr = request.remote_addr
self.remote_addr = remote_addr
Alternatively you can also just test any of the context bound objects
(such as request
or g
) for truthness:
class User(db.Model):
def __init__(self, username, remote_addr=None):
self.username = username
if remote_addr is None and request:
remote_addr = request.remote_addr
self.remote_addr = remote_addr
Changelog
New in version 0.7.
Return type:
flask.copy_current_request_context(f)¶
A helper function that decorates a function to retain the current
request context. This is useful when working with greenlets. The moment
the function is decorated a copy of the request context is created and
then pushed when the function is called. The current session is also
included in the copied request context.
Example:
import gevent
from flask import copy_current_request_context
@app.route('/')
def index():
@copy_current_request_context
def do_some_work():
# do some work here, it can access flask.request or
# flask.session like you would otherwise in the view function.
gevent.spawn(do_some_work)
return 'Regular response'
Changelog
New in version 0.10.
Parameters:
f (F) –
Return type:
flask.has_app_context()¶
Works like has_request_context()
but for the application
context. You can also just do a boolean check on the
current_app
object instead.
Changelog
New in version 0.9.
Return type:
flask.url_for(endpoint, *, _anchor=None, _method=None, _scheme=None, _external=None, **values)¶
Generate a URL to the given endpoint with the given values.
This requires an active request or application context, and calls
current_app.url_for()
. See that method
for full documentation.
Parameters:
endpoint (str) – The endpoint name associated with the URL to
generate. If this starts with a .
, the current blueprint
name (if any) will be used.
_anchor (str | None) – If given, append this as #anchor
to the URL.
_method (str | None) – If given, generate the URL associated with this
method for the endpoint.
_scheme (str | None) – If given, the URL will have this scheme if it is
external.
_external (bool | None) – If given, prefer the URL to be internal (False) or
require it to be external (True). External URLs include the
scheme and domain. When not in an active request, URLs are
external by default.
values (Any) – Values to use for the variable parts of the URL rule.
Unknown keys are appended as query string arguments, like
?a=b&c=d
.
Return type:
Changelog
Changed in version 2.2: Calls current_app.url_for
, allowing an app to override the
behavior.
Changed in version 0.10: The _scheme
parameter was added.
Changed in version 0.9: The _anchor
and _method
parameters were added.
Changed in version 0.9: Calls app.handle_url_build_error
on build errors.
flask.abort(code, *args, **kwargs)¶
Raise an HTTPException
for the given
status code.
If current_app
is available, it will call its
aborter
object, otherwise it will use
werkzeug.exceptions.abort()
.
Parameters:
code (int | Response) – The status code for the exception, which must be
registered in app.aborter
.
args (Any) – Passed to the exception.
kwargs (Any) – Passed to the exception.
Return type:
Changelog
New in version 2.2: Calls current_app.aborter
if available instead of always
using Werkzeug’s default abort
.
flask.redirect(location, code=302, Response=None)¶
Create a redirect response object.
If current_app
is available, it will use its
redirect()
method, otherwise it will use
werkzeug.utils.redirect()
.
Parameters:
location (str) – The URL to redirect to.
code (int) – The status code for the redirect.
Response (type[Response] | None) – The response class to use. Not used when
current_app
is active, which uses app.response_class
.
Return type:
Changelog
New in version 2.2: Calls current_app.redirect
if available instead of always
using Werkzeug’s default redirect
.
flask.make_response(*args)¶
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:
def index():
return render_template('index.html', foo=42)
You can now do something like this:
def index():
response = make_response(render_template('index.html', foo=42))
response.headers['X-Parachutes'] = 'parachutes are cool'
return response
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:
response = make_response(render_template('not_found.html'), 404)
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:
response = make_response(view_function())
response.headers['X-Parachutes'] = 'parachutes are cool'
Internally this function does the following things:
if no arguments are passed, it creates a new response argument
if one argument is passed,