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) –    Return type
None
property accept_charsets: werkzeug.datastructures.CharsetAccept
List of charsets this client supports as CharsetAccept object.

property accept_encodings: werkzeug.datastructures.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 accept_languages: werkzeug.datastructures.LanguageAccept
List of languages this client accepts as LanguageAccept object.

property accept_mimetypes: werkzeug.datastructures.MIMEAccept
List of mimetypes this client supports as MIMEAccept object.

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

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

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

property authorization: Optional[werkzeug.datastructures.Authorization]
The Authorization object in parsed form.

property base_url: str
Like url but without the query string.

property blueprint: Optional[str]
The name of the current blueprint

property cache_control: werkzeug.datastructures.RequestCacheControl
A RequestCacheControl object for the incoming cache control headers.

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
None

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 New in version 0.9.

property content_length: Optional[int]
The Content-Length entity-header field indicates the size of the entity-body in bytes or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

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 New in version 0.9.

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.

property cookies: ImmutableMultiDict[str, str]
A dict with the contents of all cookies transmitted with the request.

property data: bytes
Contains the incoming request data as string in case it came with a mimetype Werkzeug does not handle.

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.  Changed in version 2.0: The datetime object is timezone-aware.

dict_storage_class
alias of werkzeug.datastructures.ImmutableMultiDict

property endpoint: Optional[str]
The endpoint that matched the request. This in combination with view_args can be used to reconstruct the same or a modified URL. If an exception happened when matching, this will be None.

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

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.

form_data_parser_class
alias of werkzeug.formparser.FormDataParser

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
werkzeug.wrappers.request.Request

property full_path: str
Requested path, including the query string.

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
Union[bytes, str]

get_json(force=False, silent=False, cache=True)
Parse data as JSON. If the mimetype does not indicate JSON (application/json, see is_json()), this returns None. If parsing fails, on_json_loading_failed() is called and its return value is used as the return value.  Parameters

force (bool) – Ignore the mimetype and always try to parse JSON.
silent (bool) – Silence parsing errors and return None instead.
cache (bool) – Store the parsed JSON to return for subsequent calls.   Return type
Optional[Any]

headers
The headers received with the request.

property host: str
The host name the request was made to, including the port if it’s non-standard. Validated with trusted_hosts.

property host_url: str
The request URL scheme and host only.

property if_match: werkzeug.datastructures.ETags
An object containing all the etags in the If-Match header.  Return type
ETags

property if_modified_since: Optional[datetime.datetime]
The parsed If-Modified-Since header as a datetime object.  Changed in version 2.0: The datetime object is timezone-aware.

property if_none_match: werkzeug.datastructures.ETags
An object containing all the etags in the If-None-Match header.  Return type
ETags

property if_range: werkzeug.datastructures.IfRange
The parsed If-Range header.  Changed in version 2.0: IfRange.date is timezone-aware.   Changelog New in version 0.7.

property if_unmodified_since: Optional[datetime.datetime]
The parsed If-Unmodified-Since header as a datetime object.  Changed in version 2.0: The datetime object is timezone-aware.

input_stream
The WSGI input stream. In general it’s a bad idea to use this one because you can easily read past the boundary. Use the stream instead.

property is_json: bool
Check if the mimetype indicates JSON data, either application/json or application/*+json.

is_multiprocess
boolean that is True if the application is served by a WSGI server that spawns multiple processes.

is_multithread
boolean that is True if the application is served by a multithreaded WSGI server.

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 is_secure: bool
True if the request was made with a secure protocol (HTTPS or WSS).

property json: Optional[Any]
The parsed JSON data if mimetype indicates JSON (application/json, see is_json()). Calls get_json() with default arguments.

list_storage_class
alias of werkzeug.datastructures.ImmutableList

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
werkzeug.formparser.FormDataParser

property max_content_length: Optional[int]
Read-only view of the MAX_CONTENT_LENGTH config key.

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

method
The method the request was made with, such as GET.

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

on_json_loading_failed(e)
Called if get_json() parsing fails and isn’t silenced. If this method returns a value, it is used as the return value for get_json(). The default implementation raises BadRequest.  Parameters
e (Exception) –   Return type
NoReturn

origin
The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed.

parameter_storage_class
alias of werkzeug.datastructures.ImmutableMultiDict

path
The path part of the URL after root_path. This is the path used for routing within the application.

property pragma: werkzeug.datastructures.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.

query_string
The part of the URL after the “?”. This is the raw value, use args for the parsed values.

property range: Optional[werkzeug.datastructures.Range]
The parsed Range header.  Changelog New in version 0.7.   Return type
Range

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_addr
The address of the client sending the request.

remote_user
If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.

root_path
The prefix that the application is mounted under, without a trailing slash. path comes after this.

property root_url: str
The request URL scheme, host, and root path. This is the root that the application is accessed from.

routing_exception: Optional[Exception] = 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.

scheme
The URL scheme of the protocol the request used, such as https or wss.

property script_root: str
Alias for self.root_path. environ["SCRIPT_ROOT"] without a trailing slash.

server
The address of the server. (host, port), (path, None) for unix sockets, or None if not known.

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.

property stream: BinaryIO
If the incoming form data was not encoded with a known mimetype the data is stored unmodified in this stream for consumption. Most of the time it is a better idea to use data which will give you that data as a string. The stream only returns the data once. Unlike input_stream this stream is properly guarded that you can’t accidentally read past the length of the input. Werkzeug will internally always refer to this stream to read data which makes it possible to wrap this object with a stream that does filtering.  Changelog Changed in version 0.9: This stream is now always available but might be consumed by the form parser later on. Previously the stream was only set if no parsing happened.

property url: str
The full request URL with the scheme, host, root path, path, and query string.

property url_charset: str
The charset that is assumed for URLs. Defaults to the value of charset.  Changelog New in version 0.6.

property url_root: str
Alias for root_url. The URL with scheme, host, and root path. For example, https://example.com/app/.

url_rule: Optional[Rule] = 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 New in version 0.6.

property user_agent: werkzeug.user_agent.UserAgent
The user agent. Use user_agent.string to get the header value. Set user_agent_class to a subclass of UserAgent to provide parsing for the other properties or other extended data.  Changed in version 2.0: The built in parser is deprecated and will be removed in Werkzeug 2.1. A UserAgent subclass must be set to parse data from the string.

user_agent_class
alias of werkzeug.useragents._UserAgent

property values: CombinedMultiDict[str, str]
A werkzeug.datastructures.CombinedMultiDict that combines args and form. For GET requests, only args are present, not form.  Changed in version 2.0: For GET requests, only args are present, not form.

view_args: Optional[Dict[str, Any]] = None
A dict of view arguments that matched the request. If an exception happened when matching, this will be None.

property want_form_data_parsed: bool
True if the request method carries content. By default this is true if a Content-Type is sent.  Changelog New in version 0.8.


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


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


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 (Callable[[Request], WSGIApplication]) – the WSGI callable to decorate  Returns
a new WSGI callable  Return type
WSGIApplication


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
None


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 New in version 0.9.


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 New in version 0.9.


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.


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.  Changed in version 2.0: The datetime object is timezone-aware.


dict_storage_class
alias of werkzeug.datastructures.ImmutableMultiDict


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


form_data_parser_class
alias of werkzeug.formparser.FormDataParser


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
werkzeug.wrappers.request.Request


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
Union[bytes, str]


get_json(force=False, silent=False, cache=True)
Parse data as JSON. If the mimetype does not indicate JSON (application/json, see is_json()), this returns None. If parsing fails, on_json_loading_failed() is called and its return value is used as the return value.  Parameters

force (bool) – Ignore the mimetype and always try to parse JSON.
silent (bool) – Silence parsing errors and return None instead.
cache (bool) – Store the parsed JSON to return for subsequent calls.   Return type
Optional[Any]


headers
The headers received with the request.


input_stream
The WSGI input stream. In general it’s a bad idea to use this one because you can easily read past the boundary. Use the stream instead.


is_multiprocess
boolean that is True if the application is served by a WSGI server that spawns multiple processes.


is_multithread
boolean that is True if the application is served by a multithreaded WSGI server.


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.


list_storage_class
alias of werkzeug.datastructures.ImmutableList


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
werkzeug.formparser.FormDataParser


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


method
The method the request was made with, such as GET.


on_json_loading_failed(e)
Called if get_json() parsing fails and isn’t silenced. If this method returns a value, it is used as the return value for get_json(). The default implementation raises BadRequest.  Parameters
e (Exception) –   Return type
NoReturn


origin
The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed.


parameter_storage_class
alias of werkzeug.datastructures.ImmutableMultiDict


path
The path part of the URL after root_path. This is the path used for routing within the application.


query_string
The part of the URL after the “?”. This is the raw value, use args for the parsed values.


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_addr
The address of the client sending the request.


remote_user
If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.


root_path
The prefix that the application is mounted under, without a trailing slash. path comes after this.


routing_exception: Optional[Exception] = 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.


scheme
The URL scheme of the protocol the request used, such as https or wss.


server
The address of the server. (host, port), (path, None) for unix sockets, or None if not known.


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.


url_rule: Optional[Rule] = 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 New in version 0.6.


user_agent_class
alias of werkzeug.useragents._UserAgent


view_args: Optional[Dict[str, Any]] = None
A dict of view arguments that matched the request. If an exception happened when matching, this will be None.


class flask.ctx.RequestContext(app, environ, request=None, session=None)
The request context contains all request relevant information. It is created at the beginning of the request and pushed to the _request_ctx_stack and removed at the end of it. It will create the URL adapter and request object for the WSGI environment provided. Do not attempt to use this class directly, instead use test_request_context() and request_context() to create this object. When the request context is popped, it will evaluate all the functions registered on the application for teardown execution (teardown_request()). The request context is automatically popped at the end of the request for you. In debug mode the request context is kept around if exceptions happen so that interactive debuggers have a chance to introspect the data. With 0.4 this can also be forced for requests that did not fail and outside of DEBUG mode. By setting 'flask._preserve_context' to True on the WSGI environment the context will not pop itself at the end of the request. This is used by the test_client() for example to implement the deferred cleanup functionality. You might find this helpful for unittests where you need the information from the context local around for a little longer. Make sure to properly pop() the stack yourself in that situation, otherwise your unittests will leak memory.  Parameters

app (Flask) –
environ (dict) –
request (Optional[Request]) –
session (Optional[SessionMixin]) –    Return type
None
copy()
Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked.  Changelog Changed in version 1.1: The current session object is used instead of reloading the original data. This prevents flask.session pointing to an out-of-date object.   New in version 0.10.   Return type
flask.ctx.RequestContext

match_request()
Can be overridden by a subclass to hook into the matching of the request.  Return type
None

pop(exc=<object object>)
Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the teardown_request() decorator.  Changelog Changed in version 0.9: Added the exc argument.   Parameters
exc (Optional[BaseException]) –   Return type
None

push()
Binds the request context to the current context.  Return type
None


copy()
Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked.  Changelog Changed in version 1.1: The current session object is used instead of reloading the original data. This prevents flask.session pointing to an out-of-date object.   New in version 0.10.   Return type
flask.ctx.RequestContext


match_request()
Can be overridden by a subclass to hook into the matching of the request.  Return type
None


pop(exc=<object object>)
Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the teardown_request() decorator.  Changelog Changed in version 0.9: Added the exc argument.   Parameters
exc (Optional[BaseException]) –   Return type
None


push()
Binds the request context to the current context.  Return type
None


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

response (Union[Iterable[str], Iterable[bytes]]) –
status (Optional[Union[int, str, http.HTTPStatus]]) –
headers (werkzeug.datastructures.Headers) –
mimetype (Optional[str]) –
content_type (Optional[str]) –
direct_passthrough (bool) –    Return type
None
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 New in version 0.7.

property access_control_allow_credentials: bool
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.

access_control_allow_headers
Which headers can be sent with the cross origin request.

access_control_allow_methods
Which methods can be used for the cross origin request.

access_control_allow_origin
The origin or ‘*’ for any origin that may make cross origin requests.

access_control_expose_headers
Which headers can be shared by the browser to JavaScript code.

access_control_max_age
The maximum age in seconds the access control settings can be cached for.

add_etag(overwrite=False, weak=False)
Add an etag for the current response if there is none yet.  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
None

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: werkzeug.datastructures.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.

property cache_control: werkzeug.datastructures.ResponseCacheControl
The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.

calculate_content_length()
Returns the content length if available or None otherwise.  Return type
Optional[int]

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
func (Callable[[], Any]) –   Return type
Callable[[], Any]

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
None

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: werkzeug.datastructures.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 GET.

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: werkzeug.datastructures.ContentRange
The Content-Range header as a ContentRange object. Available even if the header is not set.  Changelog New in version 0.7.

content_security_policy
The Content-Security-Policy header adds an additional layer of security to help detect and mitigate certain types of attacks.

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

property data: Union[bytes, str]
A descriptor that calls get_data() and set_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.  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) – if the cookie that should be deleted was limited to a path, the path has to be defined here.
domain (Optional[str]) – 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 (Optional[str]) – Limit the scope of the cookie to only be attached to requests that are “same-site”.   Return type
None

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.

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.  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 (Optional[WSGIEnvironment]) – a WSGI environment object.   Returns
a response object.  Return type
Response

freeze(no_etag=None)
Make the response object ready to be pickled. Does the following:  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.   Changed in version 2.0: An ETag header is added, the no_etag parameter is deprecated and will be removed in Werkzeug 2.1.   Changelog Changed in version 0.6: The Content-Length header is set.   Parameters
no_etag (None) –   Return type
None

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
Response

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
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
Union[bytes, str]

get_etag()
Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None).  Return type
Union[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
Optional[Any]

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
werkzeug.datastructures.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[Iterable[bytes], str, List[Tuple[str, str]]]

property is_json: bool
Check if the mimetype indicates JSON data, either application/json or application/*+json.

property is_sequence: bool
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 New in version 0.6.

property is_streamed: bool
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
Iterator[bytes]

property json: Optional[Any]
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.  Changed in version 2.0: The datetime object is timezone-aware.

location
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) – a request object or WSGI environment to be used to make the response conditional against.
accept_ranges (Union[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 None, it will be set to "none". If it’s a string, it will use this value.
complete_length (Optional[int]) – 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
Response    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
None

property max_cookie_size: int
Read-only view of the MAX_COOKIE_SIZE config key. See max_cookie_size in Werkzeug’s docs.

property mimetype: Optional[str]
The mimetype (content type without charset etc.)

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 New in version 0.5.

property retry_after: Optional[datetime.datetime]
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.  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 (Optional[Union[datetime.timedelta, int]]) – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.
expires (Optional[Union[str, datetime.datetime, int, float]]) – should be a datetime object or UNIX timestamp.
path (Optional[str]) – limits the cookie to a given path, per default it will span the whole domain.
domain (Optional[str]) – 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 (Optional[str]) – Limit the scope of the cookie to only be attached to requests that are “same-site”.   Return type
None

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
value (Union[bytes, str]) –   Return type
None

set_etag(etag, weak=False)
Set the etag, and override the old one if there was one.  Parameters

etag (str) –
weak (bool) –    Return type
None

property status: str
The HTTP status code as a string.

property status_code: int
The HTTP status code as a number.

property stream: werkzeug.wrappers.response.ResponseStream
The response iterable as write-only stream.

property vary: werkzeug.datastructures.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: werkzeug.datastructures.WWWAuthenticate
The WWW-Authenticate header in a parsed form.


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 New in version 0.7.


access_control_allow_headers
Which headers can be sent with the cross origin request.


access_control_allow_methods
Which methods can be used for the cross origin request.


access_control_allow_origin
The origin or ‘*’ for any origin that may make cross origin requests.


access_control_expose_headers
Which headers can be shared by the browser to JavaScript code.


access_control_max_age
The maximum age in seconds the access control settings can be cached for.


add_etag(overwrite=False, weak=False)
Add an etag for the current response if there is none yet.  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
None


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.


calculate_content_length()
Returns the content length if available or None otherwise.  Return type
Optional[int]


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
func (Callable[[], Any]) –   Return type
Callable[[], Any]


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
None


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.


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


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


content_security_policy
The Content-Security-Policy header adds an additional layer of security to help detect and mitigate certain types of attacks.


content_security_policy_report_only
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.  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) – if the cookie that should be deleted was limited to a path, the path has to be defined here.
domain (Optional[str]) – 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 (Optional[str]) – Limit the scope of the cookie to only be attached to requests that are “same-site”.   Return type
None


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.


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.  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 (Optional[WSGIEnvironment]) – a WSGI environment object.   Returns
a response object.  Return type
Response


freeze(no_etag=None)
Make the response object ready to be pickled. Does the following:  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.   Changed in version 2.0: An ETag header is added, the no_etag parameter is deprecated and will be removed in Werkzeug 2.1.   Changelog Changed in version 0.6: The Content-Length header is set.   Parameters
no_etag (None) –   Return type
None


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
Response


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
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
Union[bytes, str]


get_etag()
Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None).  Return type
Union[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
Optional[Any]


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
werkzeug.datastructures.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[Iterable[bytes], str, List[Tuple[str, str]]]


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
Iterator[bytes]


last_modified
The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified.  Changed in version 2.0: The datetime object is timezone-aware.


location
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) – a request object or WSGI environment to be used to make the response conditional against.
accept_ranges (Union[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 None, it will be set to "none". If it’s a string, it will use this value.
complete_length (Optional[int]) – 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
Response    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
None


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 (Optional[Union[datetime.timedelta, int]]) – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.
expires (Optional[Union[str, datetime.datetime, int, float]]) – should be a datetime object or UNIX timestamp.
path (Optional[str]) – limits the cookie to a given path, per default it will span the whole domain.
domain (Optional[str]) – 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 (Optional[str]) – Limit the scope of the cookie to only be attached to requests that are “same-site”.   Return type
None


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
value (Union[bytes, str]) –   Return type
None


set_etag(etag, weak=False)
Set the etag, and override the old one if there was one.  Parameters

etag (str) –
weak (bool) –    Return type
None


flask.safe_join(directory, *pathnames)
Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory.  Parameters

directory (str) – The trusted base directory.
pathnames (str) – The untrusted path components relative to the base directory.   Returns
A safe path, otherwise None.  Return type
str


class flask.cli.ScriptInfo(app_import_path=None, create_app=None, set_debug_flag=True)
Helper object to deal with Flask applications. This is usually not necessary to interface with as it’s used internally in the dispatching to click. In future versions of Flask this object will most likely play a bigger role. Typically it’s created automatically by the FlaskGroup but you can also manually create it and pass it onwards as click object.
app_import_path
Optionally the import path for the Flask application.

create_app
Optionally a function that is passed the script info to create the instance of the application.

data
A dictionary with arbitrary data that can be associated with this script info.

load_app()
Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned.


app_import_path
Optionally the import path for the Flask application.


create_app
Optionally a function that is passed the script info to create the instance of the application.


data
A dictionary with arbitrary data that can be associated with this script info.


load_app()
Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned.


SECRET_KEY
A secret key that will be used for securely signing the session cookie and can be used for any other security related needs by extensions or your application. It should be a long random bytes or str. For example, copy the output of this to your config: $ python -c 'import os; print(os.urandom(16))'
b'_5#y2L"F4Q8z\n\xec]/'
 Do not reveal the secret key when posting questions or committing code. Default: None


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 (Any) –   Return type
None
accessed = False
header, which allows caching proxies to cache different pages for different users.

get(key, default=None)
Return the value for key if key is in the dictionary, else default.  Parameters

key (str) –
default (Optional[Any]) –    Return type
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.

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 (Optional[Any]) –    Return type
Any


accessed = False
header, which allows caching proxies to cache different pages for different users.


get(key, default=None)
Return the value for key if key is in the dictionary, else default.  Parameters

key (str) –
default (Optional[Any]) –    Return type
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.


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 (Optional[Any]) –    Return type
Any


class flask.sessions.SecureCookieSessionInterface
The default session interface that stores sessions in signed cookies through the itsdangerous module.
static digest_method()
the hash function to use for the signature. The default is sha1

key_derivation = 'hmac'
the name of the itsdangerous supported key derivation. The default is hmac.

open_session(app, request)
This method has to be implemented and must either return None in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on SessionMixin.  Parameters

app (Flask) –
request (Request) –    Return type
Optional[flask.sessions.SecureCookieSession]

salt = 'cookie-session'
the salt that should be applied on top of the secret key for the signing of cookie based sessions.

save_session(app, session, response)
This is called for actual sessions returned by open_session() at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that.  Parameters

app (Flask) –
session (flask.sessions.SessionMixin) –
response (Response) –    Return type
None

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.

session_class
alias of flask.sessions.SecureCookieSession


static digest_method()
the hash function to use for the signature. The default is sha1


key_derivation = 'hmac'
the name of the itsdangerous supported key derivation. The default is hmac.


open_session(app, request)
This method has to be implemented and must either return None in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on SessionMixin.  Parameters

app (Flask) –
request (Request) –    Return type
Optional[flask.sessions.SecureCookieSession]


salt = 'cookie-session'
the salt that should be applied on top of the secret key for the signing of cookie based sessions.


save_session(app, session, response)
This is called for actual sessions returned by open_session() at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that.  Parameters

app (Flask) –
session (flask.sessions.SessionMixin) –
response (Response) –    Return type
None


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.


session_class
alias of flask.sessions.SecureCookieSession


flask.send_file(path_or_file, mimetype=None, as_attachment=False, download_name=None, attachment_filename=None, conditional=True, etag=True, add_etags=None, last_modified=None, max_age=None, cache_timeout=None)
Send the contents of a file to the client. The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with io.BytesIO. Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn’t intend. Use send_from_directory() to safely serve user-requested paths from within a directory. If the WSGI server sets a file_wrapper in environ, it is used, otherwise Werkzeug’s built-in wrapper is used. Alternatively, if the HTTP server supports X-Sendfile, configuring Flask with USE_X_SENDFILE = True will tell the server to send the given path, which is much more efficient than reading it in Python.  Parameters

path_or_file – The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data.
mimetype – The MIME type to send for the file. If not provided, it will try to detect it from the file name.
as_attachment – Indicate to a browser that it should offer to save the file instead of displaying it.
download_name – The default name browsers will use when saving the file. Defaults to the passed file name.
conditional – Enable conditional and range responses based on request headers. Requires passing a file path and environ.
etag – Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead.
last_modified – The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path.
max_age – How long the client should cache the file, in seconds. If set, Cache-Control will be public, otherwise it will be no-cache to prefer conditional caching.     Changed in version 2.0: download_name replaces the attachment_filename parameter. If as_attachment=False, it is passed with Content-Disposition: inline instead.   Changed in version 2.0: max_age replaces the cache_timeout parameter. conditional is enabled and max_age is not set by default.   Changed in version 2.0: etag replaces the add_etags parameter. It can be a string to use instead of generating one.   Changed in version 2.0: Passing a file-like object that inherits from TextIOBase will raise a ValueError rather than sending an empty file.   New in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments.   Changelog Changed in version 1.1: filename may be a PathLike object.   Changed in version 1.1: Passing a BytesIO object supports range requests.   Changed in version 1.0.3: Filenames are encoded with ASCII instead of Latin-1 for broader compatibility with WSGI servers.   Changed in version 1.0: UTF-8 filenames as specified in RFC 2231 are supported.   Changed in version 0.12: The filename is no longer automatically inferred from file objects. If you want to use automatic MIME and etag support, pass a filename via filename_or_fp or attachment_filename.   Changed in version 0.12: attachment_filename is preferred over filename for MIME detection.   Changed in version 0.9: cache_timeout defaults to Flask.get_send_file_max_age().   Changed in version 0.7: MIME guessing and etag support for file-like objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself.   Changed in version 0.5: The add_etags, cache_timeout and conditional parameters were added. The default behavior is to add etags.   New in version 0.2.


SEND_FILE_MAX_AGE_DEFAULT
When serving files, set the cache control max age to this number of seconds. Can be a datetime.timedelta or an int. Override this value on a per-file basis using get_send_file_max_age() on the application or blueprint. If None, send_file tells the browser to use conditional requests will be used instead of a timed cache, which is usually preferable. Default: None


flask.send_from_directory(directory, path, filename=None, **kwargs)
Send a file from within a directory using send_file(). @app.route("/uploads/<path:name>")
def download_file(name):
    return send_from_directory(
        app.config['UPLOAD_FOLDER'], name, as_attachment=True
    )
 This is a secure way to serve files from a folder, such as static files or uploads. Uses safe_join() to ensure the path coming from the client is not maliciously crafted to point outside the specified directory. If the final path does not point to an existing regular file, raises a 404 NotFound error.  Parameters

directory (str) – The directory that path must be located under.
path (str) – The path to the file to send, relative to directory.
kwargs (Any) – Arguments to pass to send_file().
filename (Optional[str]) –    Return type
Response    Changed in version 2.0: path replaces the filename parameter.   New in version 2.0: Moved the implementation to Werkzeug. This is now a wrapper to pass some Flask-specific arguments.   Changelog New in version 0.5.


SERVER_NAME
Inform the application what host and port it is bound to. Required for subdomain route matching support. If set, will be used for the session cookie domain if SESSION_COOKIE_DOMAIN is not set. Modern web browsers will not allow setting cookies for domains without a dot. To use a domain locally, add any names that should route to the app to your hosts file. 127.0.0.1 localhost.dev
 If set, url_for can generate external URLs with only an application context instead of a request context. Default: None


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

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


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


new
True if the session is new, False otherwise.


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


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):
    pass
 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()
  Changelog New in version 0.8.
get_cookie_domain(app)
Returns the domain that should be set for the session cookie. Uses SESSION_COOKIE_DOMAIN if it is configured, otherwise falls back to detecting the domain based on SERVER_NAME. Once detected (or if not set at all), SESSION_COOKIE_DOMAIN is updated to avoid re-running the logic.  Parameters
app (Flask) –   Return type
Optional[str]

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
bool

get_cookie_name(app)
Returns the name of the session cookie. Uses app.session_cookie_name which is set to SESSION_COOKIE_NAME  Parameters
app (Flask) –   Return type
str

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
str

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

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
bool

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 (flask.sessions.SessionMixin) –    Return type
Optional[datetime.datetime]

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
bool

make_null_session(app)
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
flask.sessions.NullSession

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 flask.sessions.NullSession

open_session(app, request)
This method has to be implemented and must either return None in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on SessionMixin.  Parameters

app (Flask) –
request (Request) –    Return type
Optional[flask.sessions.SessionMixin]

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 New in version 0.10.

save_session(app, session, response)
This is called for actual sessions returned by open_session() at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that.  Parameters

app (Flask) –
session (flask.sessions.SessionMixin) –
response (Response) –    Return type
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 (flask.sessions.SessionMixin) –    Return type
bool


get_cookie_domain(app)
Returns the domain that should be set for the session cookie. Uses SESSION_COOKIE_DOMAIN if it is configured, otherwise falls back to detecting the domain based on SERVER_NAME. Once detected (or if not set at all), SESSION_COOKIE_DOMAIN is updated to avoid re-running the logic.  Parameters
app (Flask) –   Return type
Optional[str]


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
bool


get_cookie_name(app)
Returns the name of the session cookie. Uses app.session_cookie_name which is set to SESSION_COOKIE_NAME  Parameters
app (Flask) –   Return type
str


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
str


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


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
bool


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 (flask.sessions.SessionMixin) –    Return type
Optional[datetime.datetime]


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
bool


make_null_session(app)
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
flask.sessions.NullSession


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 flask.sessions.NullSession


open_session(app, request)
This method has to be implemented and must either return None in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on SessionMixin.  Parameters

app (Flask) –
request (Request) –    Return type
Optional[flask.sessions.SessionMixin]


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 New in version 0.10.


save_session(app, session, response)
This is called for actual sessions returned by open_session() at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that.  Parameters

app (Flask) –
session (flask.sessions.SessionMixin) –
response (Response) –    Return type
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 (flask.sessions.SessionMixin) –    Return type
bool


class flask.sessions.SessionMixin
Expands a basic dictionary with session attributes.
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.

modified = True
Some implementations can detect changes to the session and set this when that happens. The mixin default is hard coded to True.

property permanent: bool
This reflects the '_permanent' key in the dict.


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.


modified = True
Some implementations can detect changes to the session and set this when that happens. The mixin default is hard coded to True.


SESSION_COOKIE_DOMAIN
The domain match rule that the session cookie will be valid for. If not set, the cookie will be valid for all subdomains of SERVER_NAME. If False, the cookie’s domain will not be set. Default: None


SESSION_COOKIE_HTTPONLY
Browsers will not allow JavaScript access to cookies marked as “HTTP only” for security. Default: True


SESSION_COOKIE_NAME
The name of the session cookie. Can be changed in case you already have a cookie with the same name. Default: 'session'


SESSION_COOKIE_PATH
The path that the session cookie will be valid for. If not set, the cookie will be valid underneath APPLICATION_ROOT or / if that is not set. Default: None


SESSION_COOKIE_SAMESITE
Restrict how cookies are sent with requests from external sites. Can be set to 'Lax' (recommended) or 'Strict'. See Set-Cookie options. Default: None  Changelog New in version 1.0.


SESSION_COOKIE_SECURE
Browsers will only send cookies with requests over HTTPS if the cookie is marked “secure”. The application must be served over HTTPS for this to make sense. Default: False


SESSION_REFRESH_EACH_REQUEST
Control whether the cookie is sent with every response when session.permanent is true. Sending the cookie every time (the default) can more reliably keep the session from expiring, but uses more bandwidth. Non-permanent sessions are not affected. Default: True


Signals  Changelog New in version 0.6.  Starting with Flask 0.6, there is integrated support for signalling in Flask. This support is provided by the excellent blinker library and will gracefully fall back if it is not available. What are signals? Signals help you decouple applications by sending notifications when actions occur elsewhere in the core framework or another Flask extensions. In short, signals allow certain senders to notify subscribers that something happened. Flask comes with a couple of signals and other extensions might provide more. Also keep in mind that signals are intended to notify subscribers and should not encourage subscribers to modify data. You will notice that there are signals that appear to do the same thing like some of the builtin decorators do (eg: request_started is very similar to before_request()). However, there are differences in how they work. The core before_request() handler, for example, is executed in a specific order and is able to abort the request early by returning a response. In contrast all signal handlers are executed in undefined order and do not modify any data. The big advantage of signals over handlers is that you can safely subscribe to them for just a split second. These temporary subscriptions are helpful for unit testing for example. Say you want to know what templates were rendered as part of a request: signals allow you to do exactly that. Subscribing to Signals To subscribe to a signal, you can use the connect() method of a signal. The first argument is the function that should be called when the signal is emitted, the optional second argument specifies a sender. To unsubscribe from a signal, you can use the disconnect() method. For all core Flask signals, the sender is the application that issued the signal. When you subscribe to a signal, be sure to also provide a sender unless you really want to listen for signals from all applications. This is especially true if you are developing an extension. For example, here is a helper context manager that can be used in a unit test to determine which templates were rendered and what variables were passed to the template: from flask import template_rendered
from contextlib import contextmanager

@contextmanager
def captured_templates(app):
    recorded = []
    def record(sender, template, context, **extra):
        recorded.append((template, context))
    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)
 This can now easily be paired with a test client: with captured_templates(app) as templates:
    rv = app.test_client().get('/')
    assert rv.status_code == 200
    assert len(templates) == 1
    template, context = templates[0]
    assert template.name == 'index.html'
    assert len(context['items']) == 10
 Make sure to subscribe with an extra **extra argument so that your calls don’t fail if Flask introduces new arguments to the signals. All the template rendering in the code issued by the application app in the body of the with block will now be recorded in the templates variable. Whenever a template is rendered, the template object as well as context are appended to it. Additionally there is a convenient helper method (connected_to()) that allows you to temporarily subscribe a function to a signal with a context manager on its own. Because the return value of the context manager cannot be specified that way, you have to pass the list in as an argument: from flask import template_rendered

def captured_templates(app, recorded, **extra):
    def record(sender, template, context):
        recorded.append((template, context))
    return template_rendered.connected_to(record, app)
 The example above would then look like this: templates = []
with captured_templates(app, templates, **extra):
    ...
    template, context = templates[0]
  Blinker API Changes The connected_to() method arrived in Blinker with version 1.1.  Creating Signals If you want to use signals in your own application, you can use the blinker library directly. The most common use case are named signals in a custom Namespace.. This is what is recommended most of the time: from blinker import Namespace
my_signals = Namespace()
 Now you can create new signals like this: model_saved = my_signals.signal('model-saved')
 The name for the signal here makes it unique and also simplifies debugging. You can access the name of the signal with the name attribute.  For Extension Developers If you are writing a Flask extension and you want to gracefully degrade for missing blinker installations, you can do so by using the flask.signals.Namespace class.  Sending Signals If you want to emit a signal, you can do so by calling the send() method. It accepts a sender as first argument and optionally some keyword arguments that are forwarded to the signal subscribers: class Model(object):
    ...

    def save(self):
        model_saved.send(self)
 Try to always pick a good sender. If you have a class that is emitting a signal, pass self as sender. If you are emitting a signal from a random function, you can pass current_app._get_current_object() as sender.  Passing Proxies as Senders Never pass current_app as sender to a signal. Use current_app._get_current_object() instead. The reason for this is that current_app is a proxy and not the real application object.  Signals and Flask’s Request Context Signals fully support The Request Context when receiving signals. Context-local variables are consistently available between request_started and request_finished, so you can rely on flask.g and others as needed. Note the limitations described in Sending Signals and the request_tearing_down signal. Decorator Based Signal Subscriptions With Blinker 1.1 you can also easily subscribe to signals by using the new connect_via() decorator: from flask import template_rendered

@template_rendered.connect_via(app)
def when_template_rendered(sender, template, context, **extra):
    print f'Template {template.name} is rendered with {context}'
 Core Signals Take a look at Signals for a list of all builtin signals.


flask.stream_with_context(generator_or_function)
Request contexts disappear when the response is started on the server. This is done for efficiency reasons and to make it less likely to encounter memory leaks with badly written WSGI middlewares. The downside is that if you are using streamed responses, the generator cannot access request bound information any more. This function however can help you keep the context around for longer: from flask import stream_with_context, request, Response

@app.route('/stream')
def streamed_response():
    @stream_with_context
    def generate():
        yield 'Hello '
        yield request.args['name']
        yield '!'
    return Response(generate())
 Alternatively it can also be used around a specific generator: from flask import stream_with_context, request, Response

@app.route('/stream')
def streamed_response():
    def generate():
        yield 'Hello '
        yield request.args['name']
        yield '!'
    return Response(stream_with_context(generate()))
  Changelog New in version 0.9.   Parameters
generator_or_function (Union[Generator, Callable]) –   Return type
Generator


class flask.json.tag.TaggedJSONSerializer
Serializer that uses a tag system to compactly represent objects that are not JSON types. Passed as the intermediate serializer to itsdangerous.Serializer. The following extra types are supported:  dict tuple bytes Markup UUID datetime   Return type
None
default_tags = [<class 'flask.json.tag.TagDict'>, <class 'flask.json.tag.PassDict'>, <class 'flask.json.tag.TagTuple'>, <class 'flask.json.tag.PassList'>, <class 'flask.json.tag.TagBytes'>, <class 'flask.json.tag.TagMarkup'>, <class 'flask.json.tag.TagUUID'>, <class 'flask.json.tag.TagDateTime'>]
Tag classes to bind when creating the serializer. Other tags can be added later using register().

dumps(value)
Tag the value and dump it to a compact JSON string.  Parameters
value (Any) –   Return type
str

loads(value)
Load data from a JSON string and deserialized any tagged objects.  Parameters
value (str) –   Return type
Any

register(tag_class, force=False, index=None)
Register a new tag with this serializer.  Parameters

tag_class (Type[flask.json.tag.JSONTag]) – tag class to register. Will be instantiated with this serializer instance.
force (bool) – overwrite an existing tag. If false (default), a KeyError is raised.
index (Optional[int]) – index to insert the new tag in the tag order. Useful when the new tag is a special case of an existing tag. If None (default), the tag is appended to the end of the order.   Raises
KeyError – if the tag key is already registered and force is not true.  Return type
None

tag(value)
Convert a value to a tagged representation if necessary.  Parameters
value (Any) –   Return type
Dict[str, Any]

untag(value)
Convert a tagged representation back to the original type.  Parameters
value (Dict[str, Any]) –   Return type
Any