This reads the buffered incoming data from the client into one bytes object. By default this is cached but that behavior can be changed by setting cache to False.
Usually it’s a bad idea to call this method without checking the content length first as a client could send dozens of megabytes or more to cause memory problems on the server.
Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set parse_form_data to True. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory.
If as_text is set to True the return value will be a decoded string.
New in version 0.9.
Union[bytes, str]


Parse data as JSON.
If the mimetype does not indicate JSON (application/json, see is_json()), this returns None.
If parsing fails, on_json_loading_failed() is called and its return value is used as the return value.
Optional[Any]


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


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


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


boolean that is True if the application will be executed only once in a process lifetime. This is the case for CGI for example, but it’s not guaranteed that the execution only happens one time.


Creates the form data parser. Instantiates the form_data_parser_class with some parameters.
New in version 0.8.
werkzeug.formparser.FormDataParser


The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server.


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


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


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


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


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


The Referer[sic] request-header field allows the client to specify, for the server’s benefit, the address (URI) of the resource from which the Request-URI was obtained (the “referrer”, although the header field is misspelled).


The address of the client sending the request.


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


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


If matching the URL failed, this is the exception that will be raised / was raised as part of the request handling. This is usually a NotFound exception or something similar.


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


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


Set when creating the request object. If True, reading from the request body will cause a RuntimeException. Useful to prevent modifying the stream from middleware.


The internal URL rule that matched the request. This can be useful to inspect which methods are allowed for the URL from a before/after handler (request.url_rule.methods) etc. Though if the request’s method was invalid for the URL rule, the valid list is available in routing_exception.valid_methods instead (an attribute of the Werkzeug exception MethodNotAllowed) because the request was never internally bound.
New in version 0.6.


A dict of view arguments that matched the request. If an exception happened when matching, this will be 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.
None
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.
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.
flask.ctx.RequestContext
Can be overridden by a subclass to hook into the matching of the request.
None
Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the teardown_request() decorator.
Changed in version 0.9: Added the exc argument.
exc (Optional[BaseException]) –
None
Binds the request context to the current context.
None


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.
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.
flask.ctx.RequestContext


Can be overridden by a subclass to hook into the matching of the request.
None


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


Binds the request context to the current context.
None


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.
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.
None
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.
New in version 0.7.
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.
Which headers can be sent with the cross origin request.
Which methods can be used for the cross origin request.
The origin or ‘*’ for any origin that may make cross origin requests.
Which headers can be shared by the browser to JavaScript code.
The maximum age in seconds the access control settings can be cached for.
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.
None
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.
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.
The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.
Returns the content length if available or None otherwise.
Optional[int]
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.
New in version 0.6.
func (Callable[[], Any]) –
Callable[[], Any]
Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.
New in version 0.9: Can now be used in a with statement.
None
The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.
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.
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.
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.
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.)
The Content-Range header as a ContentRange object. Available even if the header is not set.
New in version 0.7.
The Content-Security-Policy header adds an additional layer of security to help detect and mitigate certain types of attacks.
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.
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.
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.
Allows control over sharing of browsing context group with cross-origin documents. Values must be a member of the werkzeug.http.COOP enum.
A descriptor that calls get_data() and set_data().
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 a cookie. Fails silently if key doesn’t exist.
None
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.
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.
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:
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!
a response object.
Response
Make the response object ready to be pickled. Does the following:
Changed in version 2.0: An ETag header is added, the no_etag parameter is deprecated and will be removed in Werkzeug 2.1.
Changed in version 0.6: The Content-Length header is set.
no_etag (None) –
None
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.
a response object.
Response
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.
New in version 0.6.
environ (WSGIEnvironment) – the WSGI environment of the request.
a response iterable.
Iterable[bytes]
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.
New in version 0.9.
as_text (bool) –
Union[bytes, str]
Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None).
Union[Tuple[str, bool], Tuple[None, None]]
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.
Optional[Any]
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.
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.
environ (WSGIEnvironment) – the WSGI environment of the request.
returns a new Headers object.
werkzeug.datastructures.Headers
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.
New in version 0.6.
environ (WSGIEnvironment) – the WSGI environment of the request.
an (app_iter, status, headers) tuple.
Tuple[Iterable[bytes], str, List[Tuple[str, str]]]
Check if the mimetype indicates JSON data, either application/json or application/*+json.
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.
New in version 0.6.
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 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.
Iterator[bytes]
The parsed JSON data if mimetype indicates JSON (application/json, see is_json()).
Calls get_json() with default arguments.
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.
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 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.
RequestedRangeNotSatisfiable if Range header could not be parsed or satisfied.
Response
Changed in version 2.0: Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error.
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.
New in version 0.6.
None
Read-only view of the MAX_COOKIE_SIZE config key.
See max_cookie_size in Werkzeug’s docs.
The mimetype (content type without charset etc.)
The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.
New in version 0.5.
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.
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.
None
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).
New in version 0.9.
value (Union[bytes, str]) –
None
Set the etag, and override the old one if there was one.
None
The HTTP status code as a string.
The HTTP status code as a number.
The response iterable as write-only stream.
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.
The WWW-Authenticate header in a parsed form.


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


Which headers can be sent with the cross origin request.


Which methods can be used for the cross origin request.


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


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


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


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


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.


Returns the content length if available or None otherwise.
Optional[int]


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.
New in version 0.6.
func (Callable[[], Any]) –
Callable[[], Any]


Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.
New in version 0.9: Can now be used in a with statement.
None


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


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.


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.


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


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


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.


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.


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.


Allows control over sharing of browsing context group with cross-origin documents. Values must be a member of the werkzeug.http.COOP enum.


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 a cookie. Fails silently if key doesn’t exist.
None


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.


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.


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:
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!
a response object.
Response


Make the response object ready to be pickled. Does the following:
Changed in version 2.0: An ETag header is added, the no_etag parameter is deprecated and will be removed in Werkzeug 2.1.
Changed in version 0.6: The Content-Length header is set.
no_etag (None) –
None


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.
a response object.
Response


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.
New in version 0.6.
environ (WSGIEnvironment) – the WSGI environment of the request.
a response iterable.
Iterable[bytes]


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.
New in version 0.9.
as_text (bool) –
Union[bytes, str]


Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None).
Union[Tuple[str, bool], Tuple[None, None]]


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.
Optional[Any]


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.
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.
environ (WSGIEnvironment) – the WSGI environment of the request.
returns a new Headers object.
werkzeug.datastructures.Headers


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.
New in version 0.6.
environ (WSGIEnvironment) – the WSGI environment of the request.
an (app_iter, status, headers) tuple.
Tuple[Iterable[bytes], str, List[Tuple[str, str]]]


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


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.


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 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.
RequestedRangeNotSatisfiable if Range header could not be parsed or satisfied.
Response
Changed in version 2.0: Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error.


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


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).
New in version 0.9.
value (Union[bytes, str]) –
None


Set the etag, and override the old one if there was one.
None


Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory.
A safe path, otherwise None.
str


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.
Optionally the import path for the Flask application.
Optionally a function that is passed the script info to create the instance of the application.
A dictionary with arbitrary data that can be associated with this script info.
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.


Optionally the import path for the Flask application.


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


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


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.


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:
Do not reveal the secret key when posting questions or committing code.
Default: 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.
initial (Any) –
None
header, which allows caching proxies to cache different pages for different users.
Return the value for key if key is in the dictionary, else default.
Any
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.
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.
Any


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


Return the value for key if key is in the dictionary, else default.
Any


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.


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


The default session interface that stores sessions in signed cookies through the itsdangerous module.
the hash function to use for the signature. The default is sha1
the name of the itsdangerous supported key derivation. The default is hmac.
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.
Optional[flask.sessions.SecureCookieSession]
the salt that should be applied on top of the secret key for the signing of cookie based sessions.
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.
None
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.
alias of flask.sessions.SecureCookieSession


the hash function to use for the signature. The default is sha1


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


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.
Optional[flask.sessions.SecureCookieSession]


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


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


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.


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


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


Send a file from within a directory using send_file().
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.
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.
New in version 0.5.


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.
If set, url_for can generate external URLs with only an application context instead of a request context.
Default: None


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:
True if the session is new, False otherwise.
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:
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.


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:


True if the session is new, False otherwise.


If set to True the session lives for permanent_session_lifetime seconds. The default is 31 days. If set to False (which is the default) the session will be deleted when the user closes the browser.


The 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:
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:
New in version 0.8.
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.
app (Flask) –
Optional[str]
Returns True if the session cookie should be httponly. This currently just returns the value of the SESSION_COOKIE_HTTPONLY config var.
app (Flask) –
bool
Returns the name of the session cookie.
Uses app.session_cookie_name which is set to SESSION_COOKIE_NAME
app (Flask) –
str
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.
app (Flask) –
str
Return 'Strict' or 'Lax' if the cookie should use the SameSite attribute. This currently just returns the value of the SESSION_COOKIE_SAMESITE setting.
app (Flask) –
str
Returns True if the cookie should be secure. This currently just returns the value of the SESSION_COOKIE_SECURE setting.
app (Flask) –
bool
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.
Optional[datetime.datetime]
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.
obj (object) –
bool
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.
app (Flask) –
flask.sessions.NullSession
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
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.
Optional[flask.sessions.SessionMixin]
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.
New in version 0.10.
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.
None
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.
New in version 0.11.
bool


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.
app (Flask) –
Optional[str]


Returns True if the session cookie should be httponly. This currently just returns the value of the SESSION_COOKIE_HTTPONLY config var.
app (Flask) –
bool


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


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.
app (Flask) –
str


Return 'Strict' or 'Lax' if the cookie should use the SameSite attribute. This currently just returns the value of the SESSION_COOKIE_SAMESITE setting.
app (Flask) –
str


Returns True if the cookie should be secure. This currently just returns the value of the SESSION_COOKIE_SECURE setting.
app (Flask) –
bool


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.
Optional[datetime.datetime]


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.
obj (object) –
bool


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


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


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.
Optional[flask.sessions.SessionMixin]


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


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


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


Expands a basic dictionary with session attributes.
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.
Some implementations can detect changes to the session and set this when that happens. The mixin default is hard coded to True.
This reflects the '_permanent' key in the dict.


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.


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


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


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


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


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


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


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


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


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.
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:
This can now easily be paired with a test client:
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:
The example above would then look like this:
Blinker API Changes
The connected_to() method arrived in Blinker with version 1.1.
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:
Now you can create new signals like this:
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.
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:
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 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.
With Blinker 1.1 you can also easily subscribe to signals by using the new connect_via() decorator:
Take a look at Signals for a list of all builtin signals.


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:
Alternatively it can also be used around a specific generator:
New in version 0.9.
generator_or_function (Union[Generator, Callable]) –
Generator


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:
None
Tag classes to bind when creating the serializer. Other tags can be added later using register().
Tag the value and dump it to a compact JSON string.
value (Any) –
str
Load data from a JSON string and deserialized any tagged objects.
value (str) –
Any
Register a new tag with this serializer.
KeyError – if the tag key is already registered and force is not true.
None
Convert a value to a tagged representation if necessary.
value (Any) –
Dict[str, Any]
Convert a tagged representation back to the original type.
value (Dict[str, Any]) –
Any


Tag classes to bind when creating the serializer. Other tags can be added later using register().


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


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


Register a new tag with this serializer.
KeyError – if the tag key is already registered and force is not true.
None


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


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


Flask leverages Jinja2 as its template engine. You are obviously free to use a different template engine, but you still have to install Jinja2 to run Flask itself. This requirement is necessary to enable rich extensions. An extension can depend on Jinja2 being present.
This section only gives a very quick introduction into how Jinja2 is integrated into Flask. If you want information on the template engine’s syntax itself, head over to the official Jinja2 Template Documentation for more information.
Unless customized, Jinja2 is configured by Flask as follows:
The following global variables are available within Jinja2 templates by default:
The current configuration object (flask.config)
Changed in version 0.10: This is now always available, even in imported templates.
New in version 0.6.
The current request object (flask.request). This variable is unavailable if the template was rendered without an active request context.
The current session object (flask.session). This variable is unavailable if the template was rendered without an active request context.
The request-bound object for global variables (flask.g). This variable is unavailable if the template was rendered without an active request context.
The flask.url_for() function.
The flask.get_flashed_messages() function.
The Jinja Context Behavior
These variables are added to the context of variables, they are not global variables. The difference is that by default these will not show up in the context of imported templates. This is partially caused by performance considerations, partially to keep things explicit.
What does this mean for you? If you have a macro you want to import, that needs to access the request object you have two possibilities:
Importing with context looks like this:
Autoescaping is the concept of automatically escaping special characters for you. Special characters in the sense of HTML (or XML, and thus XHTML) are &, >, <, " as well as '. Because these characters carry specific meanings in documents on their own you have to replace them by so called “entities” if you want to use them for text. Not doing so would not only cause user frustration by the inability to use these characters in text, but can also lead to security problems. (see Cross-Site Scripting (XSS))
Sometimes however you will need to disable autoescaping in templates. This can be the case if you want to explicitly inject HTML into pages, for example if they come from a system that generates secure HTML like a markdown to HTML converter.
There are three ways to accomplish that:
To disable the autoescape system in templates, you can use the {%
autoescape %} block:
Whenever you do this, please be very cautious about the variables you are using in this block.
If you want to register your own filters in Jinja2 you have two ways to do that. You can either put them by hand into the jinja_env of the application or use the template_filter() decorator.
The two following examples work the same and both reverse an object:
In case of the decorator the argument is optional if you want to use the function name as name of the filter. Once registered, you can use the filter in your templates in the same way as Jinja2’s builtin filters, for example if you have a Python list in context called mylist:
To inject new variables automatically into the context of a template, context processors exist in Flask. Context processors run before the template is rendered and have the ability to inject new values into the template context. A context processor is a function that returns a dictionary. The keys and values of this dictionary are then merged with the template context, for all templates in the app:
The context processor above makes a variable called user available in the template with the value of g.user. This example is not very interesting because g is available in templates anyways, but it gives an idea how this works.
Variables are not limited to values; a context processor can also make functions available to templates (since Python allows passing around functions):
The context processor above makes the format_price function available to all templates:
You could also build format_price as a template filter (see Registering Filters), but this demonstrates how to pass functions in a context processor.


Reload templates when they are changed. If not set, it will be enabled in debug mode.
Default: None


Enable testing mode. Exceptions are propagated rather than handled by the the app’s error handlers. Extensions may also change their behavior to facilitate easier testing. You should enable this in your own tests.
Default: False


Trying to access a key that doesn’t exist from request dicts like args and form will return a 400 Bad Request error page. Enable this to treat the error as an unhandled exception instead so that you get the interactive debugger. This is a more specific version of TRAP_HTTP_EXCEPTIONS. If unset, it is enabled in debug mode.
Default: None


If there is no handler for an HTTPException-type exception, re-raise it to be handled by the interactive debugger instead of returning it as a simple error response.
Default: False


Generates a URL to the given endpoint with the method provided.
Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments. If the value of a query argument is None, the whole pair is skipped. In case blueprints are active you can shortcut references to the same blueprint by prefixing the local endpoint with a dot (.).
This will reference the index function local to the current blueprint:
See URL Building.
Configuration values APPLICATION_ROOT and SERVER_NAME are only used when generating URLs outside of a request context.
To integrate applications, Flask has a hook to intercept URL build errors through Flask.url_build_error_handlers. The url_for function results in a BuildError when the current app does not have a URL for the given endpoint and values. When it does, the current_app calls its url_build_error_handlers if it is not None, which can return a string to use as the result of url_for (instead of url_for’s default to raise the BuildError exception) or re-raise the exception. An example:
Here, error is the instance of BuildError, and endpoint and values are the arguments passed into url_for. Note that this is for building URLs outside the current application, and not for handling 404 NotFound errors.
New in version 0.10: The _scheme parameter was added.
New in version 0.9: The _anchor and _method parameters were added.
New in version 0.9: Calls Flask.handle_build_error() on BuildError.
str


When serving files, set the X-Sendfile header instead of serving the data with Flask. Some web servers, such as Apache, recognize this and serve the data more efficiently. This only makes sense when using such a server.
Default: False


uWSGI is a deployment option on servers like nginx, lighttpd, and cherokee; see FastCGI and Standalone WSGI Containers for other options. To use your WSGI application with uWSGI protocol you will need a uWSGI server first. uWSGI is both a protocol and an application server; the application server can serve uWSGI, FastCGI, and HTTP protocols.
The most popular uWSGI server is uwsgi, which we will use for this guide. Make sure to have it installed to follow along.
Watch Out
Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ ==
'__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to uWSGI.
uwsgi is designed to operate on WSGI callables found in python modules.
Given a flask application in myapp.py, use the following command:
The --manage-script-name will move the handling of SCRIPT_NAME to uwsgi, since it is smarter about that. It is used together with the --mount directive which will make requests to /yourapplication be directed to myapp:app. If your application is accessible at root level, you can use a single / instead of /yourapplication. myapp refers to the name of the file of your flask application (without extension) or the module which provides app. app is the callable inside of your application (usually the line reads app = Flask(__name__).
If you want to deploy your flask application inside of a virtual environment, you need to also add --virtualenv /path/to/virtual/environment. You might also need to add --plugin python or --plugin python3 depending on which python version you use for your project.
A basic flask nginx configuration looks like this:
This configuration binds the application to /yourapplication. If you want to have it in the URL root its a bit simpler:


Alternative way to use view functions. A subclass has to implement dispatch_request() which is called with the view arguments from the URL routing system. If methods is provided the methods do not have to be passed to the add_url_rule() method explicitly:
When you want to decorate a pluggable view you will have to either do that when the view function is created (by wrapping the return value of as_view()) or you can use the decorators attribute:
The decorators stored in the decorators list are applied one after another when the view function is created. Note that you can not use the class based decorators since those would decorate the view class and not the generated view function!
Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the View on each request and call the dispatch_request() method on it.
The arguments passed to as_view() are forwarded to the constructor of the class.
Callable
The canonical way to decorate class-based views is to decorate the return value of as_view(). However since this moves parts of the logic from the class declaration to the place where it’s hooked into the routing system.
You can place one or more decorators in this list and whenever the view function is created the result is automatically decorated.
New in version 0.8.
Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.
Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]
A list of methods this view can handle.
Setting this disables or force-enables the automatic options handling.


Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the View on each request and call the dispatch_request() method on it.
The arguments passed to as_view() are forwarded to the constructor of the class.
Callable


The canonical way to decorate class-based views is to decorate the return value of as_view(). However since this moves parts of the logic from the class declaration to the place where it’s hooked into the routing system.
You can place one or more decorators in this list and whenever the view function is created the result is automatically decorated.
New in version 0.8.


Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.
Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]


Setting this disables or force-enables the automatic options handling.


Wraps a callback so that it’s guaranteed to be executed with the script’s application context. If callbacks are registered directly to the app.cli object then they are wrapped with this function by default unless it’s disabled.


A plain object. Used as a namespace for storing data during an application context.
Creating an app context automatically creates this object, which is made available as the g proxy.
Check whether an attribute is present.
New in version 0.10.
Return an iterator over the attribute names.
New in version 0.10.
Get an attribute by name, or a default value. Like dict.get().
Any
New in version 0.10.
Get and remove an attribute by name. Like dict.pop().
Any
New in version 0.11.
Get the value of an attribute if it is present, otherwise set and return a default value. Like dict.setdefault().
Any
New in version 0.11.


Get an attribute by name, or a default value. Like dict.get().
Any
New in version 0.10.


Get and remove an attribute by name. Like dict.pop().
Any
New in version 0.11.


Get the value of an attribute if it is present, otherwise set and return a default value. Like dict.setdefault().
Any
New in version 0.11.


This decorator can be used for setting specific attributes on custom action functions that can be used with actions:
This is equivalent to setting some attributes (with the original, longer names) on the function directly:
Use of this decorator is not compulsory to make an action function, but it can be useful to use it without arguments as a marker in your source to identify the purpose of the function:
In this case it will add no attributes to the function.


A Django administrative site is represented by an instance of django.contrib.admin.sites.AdminSite; by default, an instance of this class is created as django.contrib.admin.site and you can register your models and ModelAdmin instances with it.
If you want to customize the default admin site, you can override it.
When constructing an instance of an AdminSite, you can provide a unique instance name using the name argument to the constructor. This instance name is used to identify the instance, especially when reversing admin URLs. If no instance name is provided, a default instance name of admin will be used. See Customizing the AdminSite class for an example of customizing the AdminSite class.


Some actions are best if they’re made available to any object in the admin site – the export action defined above would be a good candidate. You can make an action globally available using AdminSite.add_action(). For example:
This makes the export_selected_objects action globally available as an action named “export_selected_objects”. You can explicitly give the action a name – good if you later want to programmatically remove the action – by passing a second argument to AdminSite.add_action():


Path to a custom template that will be used by the admin site app index view.


If you need to disable a site-wide action you can call AdminSite.disable_action().
For example, you can use this method to remove the built-in “delete selected objects” action:
Once you’ve done the above, that action will no longer be available site-wide.
If, however, you need to re-enable a globally-disabled action for one particular model, list it explicitly in your ModelAdmin.actions list:


Returns a dictionary of variables to put in the template context for every page in the admin site.
Includes the following variables and values by default:
available_apps: a list of applications from the application registry available for the current user. Each entry in the list is a dict representing an application with the following keys:
Each model is a dict with the following keys:
The model variable for each model was added.


The string to use for displaying empty values in the admin site’s change list. Defaults to a dash. The value can also be overridden on a per ModelAdmin basis and on a custom field within a ModelAdmin by setting an empty_value_display attribute on the field. See ModelAdmin.empty_value_display for examples.


A boolean value that determines whether to show the navigation sidebar on larger screens. By default, it is set to True.


A boolean value that determines whether to add a final catch-all view to the admin that redirects unauthenticated users to the login page. By default, it is set to True.
Warning
Setting this to False is not recommended as the view protects against a potential model enumeration privacy issue.


Returns True if the user for the given HttpRequest has permission to view at least one page in the admin site. Defaults to requiring both User.is_active and User.is_staff to be True.


Path to a custom template that will be used by the admin site main index view.


The text to put at the top of the admin index page (a string). By default, this is “Site administration”.


Subclass of AuthenticationForm that will be used by the admin site login view.


Path to a custom template that will be used by the admin site login view.


Path to a custom template that will be used by the admin site logout view.


Path to a custom template that will be used by the admin site password change done view.


Path to a custom template that will be used by the admin site password change view.


Registers the given model class (or iterable of classes) with the given admin_class. admin_class defaults to ModelAdmin (the default admin options). If keyword arguments are given – e.g. list_display – they’ll be applied as options to the admin class.
Raises ImproperlyConfigured if a model is abstract. and django.contrib.admin.sites.AlreadyRegistered if a model is already registered.


The text to put at the top of each admin page, as an <h1> (a string). By default, this is “Django administration”.


The text to put at the end of each admin page’s <title> (a string). By default, this is “Django site admin”.


The URL for the “View site” link at the top of each admin page. By default, site_url is /. Set it to None to remove the link.
For sites running on a subpath, the each_context() method checks if the current request has request.META['SCRIPT_NAME'] set and uses that value if site_url isn’t set to something other than /.


Unregisters the given model class (or iterable of classes).
Raises django.contrib.admin.sites.NotRegistered if a model isn’t already registered.


This is the default AppConfig class for the admin. It calls autodiscover() when Django starts.


This class works like AdminConfig, except it doesn’t call autodiscover().
A dotted import path to the default admin site’s class or to a callable that returns a site instance. Defaults to 'django.contrib.admin.sites.AdminSite'. See Overriding the default admin site for usage.


A dotted import path to the default admin site’s class or to a callable that returns a site instance. Defaults to 'django.contrib.admin.sites.AdminSite'. See Overriding the default admin site for usage.


This function attempts to import an admin module in each installed application. Such modules are expected to register models with the admin.
Typically you won’t need to call this function directly as AdminConfig calls it when Django starts.


This decorator can be used for setting specific attributes on custom display functions that can be used with list_display or readonly_fields:
This is equivalent to setting some attributes (with the original, longer names) on the function directly:
Also note that the empty_value decorator parameter maps to the empty_value_display attribute assigned directly to the function. It cannot be used in conjunction with boolean – they are mutually exclusive.
Use of this decorator is not compulsory to make a display function, but it can be useful to use it without arguments as a marker in your source to identify the purpose of the function:
In this case it will add no attributes to the function.


Specifies whether or not inline objects can be deleted in the inline. Defaults to True.


A list or tuple containing extra CSS classes to apply to the fieldset that is rendered for the inlines. Defaults to None. As with classes configured in fieldsets, inlines with a collapse class will be initially collapsed and their header will have a small “show” link.


This controls the number of extra forms the formset will display in addition to the initial forms. Defaults to 3. See the formsets documentation for more information.
For users with JavaScript-enabled browsers, an “Add another” link is provided to enable any number of additional inlines to be added in addition to those provided as a result of the extra argument.
The dynamic link will not appear if the number of currently displayed forms exceeds max_num, or if the user does not have JavaScript enabled.
InlineModelAdmin.get_extra() also allows you to customize the number of extra forms.


The name of the foreign key on the model. In most cases this will be dealt with automatically, but fk_name must be specified explicitly if there are more than one foreign key to the same parent model.


The value for form defaults to ModelForm. This is what is passed through to inlineformset_factory() when creating the formset for this inline.


This defaults to BaseInlineFormSet. Using your own formset can give you many possibilities of customization. Inlines are built around model formsets.


Returns the number of extra inline forms to use. By default, returns the InlineModelAdmin.extra attribute.
Override this method to programmatically determine the number of extra inline forms. For example, this may be based on the model instance (passed as the keyword argument obj):


Returns a BaseInlineFormSet class for use in admin add/change views. obj is the parent object being edited or None when adding a new parent. See the example for ModelAdmin.get_formsets_with_inlines.


Returns the maximum number of extra inline forms to use. By default, returns the InlineModelAdmin.max_num attribute.
Override this method to programmatically determine the maximum number of inline forms. For example, this may be based on the model instance (passed as the keyword argument obj):


Returns the minimum number of inline forms to use. By default, returns the InlineModelAdmin.min_num attribute.
Override this method to programmatically determine the minimum number of inline forms. For example, this may be based on the model instance (passed as the keyword argument obj).


Should return True if adding an inline object is permitted, False otherwise. obj is the parent object being edited or None when adding a new parent.


Should return True if editing an inline object is permitted, False otherwise. obj is the parent object being edited.


Should return True if deleting an inline object is permitted, False otherwise. obj is the parent object being edited.


This controls the maximum number of forms to show in the inline. This doesn’t directly correlate to the number of objects, but can if the value is small enough. See Limiting the number of editable objects for more information.
InlineModelAdmin.get_max_num() also allows you to customize the maximum number of extra forms.


This controls the minimum number of forms to show in the inline. See modelformset_factory() for more information.
InlineModelAdmin.get_min_num() also allows you to customize the minimum number of displayed forms.


The model which the inline is using. This is required.


By default, Django’s admin uses a select-box interface (<select>) for fields that are ForeignKey. Sometimes you don’t want to incur the overhead of having to select all the related instances to display in the drop-down.
raw_id_fields is a list of fields you would like to change into an Input widget for either a ForeignKey or ManyToManyField:


Specifies whether or not inline objects that can be changed in the admin have a link to the change form. Defaults to False.


The template used to render the inline on the page.


An override to the verbose_name from the model’s inner Meta class.


An override to the verbose_name_plural from the model’s inner Meta class. If this isn’t given and the InlineModelAdmin.verbose_name is defined, Django will use InlineModelAdmin.verbose_name + 's'.
The fallback to InlineModelAdmin.verbose_name was added.


The ModelAdmin class is the representation of a model in the admin interface. Usually, these are stored in a file named admin.py in your application. Let’s take a look at an example of the ModelAdmin:
Do you need a ModelAdmin object at all?
In the preceding example, the ModelAdmin class doesn’t define any custom values (yet). As a result, the default admin interface will be provided. If you are happy with the default admin interface, you don’t need to define a ModelAdmin object at all – you can register the model class without providing a ModelAdmin description. The preceding example could be simplified to:


A list of actions to make available on the change list page. See Admin actions for details.


Controls where on the page the actions bar appears. By default, the admin changelist displays actions at the top of the page (actions_on_top = True;
actions_on_bottom = False).


Controls whether a selection counter is displayed next to the action dropdown. By default, the admin changelist will display it (actions_selection_counter = True).


Path to a custom template, used by add_view().


Django view for the model instance addition page. See note below.


autocomplete_fields is a list of ForeignKey and/or ManyToManyField fields you would like to change to Select2 autocomplete inputs.
By default, the admin uses a select-box interface (<select>) for those fields. Sometimes you don’t want to incur the overhead of selecting all the related instances to display in the dropdown.
The Select2 input looks similar to the default input but comes with a search feature that loads the options asynchronously. This is faster and more user-friendly if the related model has many instances.
You must define search_fields on the related object’s ModelAdmin because the autocomplete search uses it.
To avoid unauthorized data disclosure, users must have the view or change permission to the related object in order to use autocomplete.
Ordering and pagination of the results are controlled by the related ModelAdmin’s get_ordering() and get_paginator() methods.
In the following example, ChoiceAdmin has an autocomplete field for the ForeignKey to the Question. The results are filtered by the question_text field and ordered by the date_created field:
Performance considerations for large datasets
Ordering using ModelAdmin.ordering may cause performance problems as sorting on a large queryset will be slow.
Also, if your search fields include fields that aren’t indexed by the database, you might encounter poor performance on extremely large tables.
For those cases, it’s a good idea to write your own ModelAdmin.get_search_results() implementation using a full-text indexed search.
You may also want to change the Paginator on very large tables as the default paginator always performs a count() query. For example, you could override the default implementation of the Paginator.count property.


Path to a custom template, used by change_view().


Path to a custom template, used by changelist_view().


Django view for the model instance editing page. See note below.


Django view for the model instances change list/actions page. See note below.


Set date_hierarchy to the name of a DateField or DateTimeField in your model, and the change list page will include a date-based drilldown navigation by that field.
Example:
You can also specify a field on a related model using the __ lookup, for example:
This will intelligently populate itself based on available data, e.g. if all the dates are in one month, it’ll show the day-level drill-down only.
Note
date_hierarchy uses QuerySet.datetimes() internally. Please refer to its documentation for some caveats when time zone support is enabled (USE_TZ = True).


Path to a custom template, used by delete_view() for displaying a confirmation page when deleting one or more objects.


The delete_model method is given the HttpRequest and a model instance. Overriding this method allows doing pre- or post-delete operations. Call super().delete_model() to delete the object using Model.delete().


The delete_queryset() method is given the HttpRequest and a QuerySet of objects to be deleted. Override this method to customize the deletion process for the “delete selected objects” action.


Path to a custom template, used by the delete_selected action method for displaying a confirmation page when deleting one or more objects. See the actions documentation.


Django view for the model instance(s) deletion confirmation page. See note below.


This attribute overrides the default display value for record’s fields that are empty (None, empty string, etc.). The default value is - (a dash). For example:
You can also override empty_value_display for all admin pages with AdminSite.empty_value_display, or for specific fields like this:
The empty_value argument to the display() decorator is equivalent to setting the empty_value_display attribute on the display function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.


This attribute, if given, should be a list of field names to exclude from the form.
For example, let’s consider the following model:
If you want a form for the Author model that includes only the name and title fields, you would specify fields or exclude like this:
Since the Author model only has three fields, name, title, and birth_date, the forms resulting from the above declarations will contain exactly the same fields.


Use the fields option to make simple layout changes in the forms on the “add” and “change” pages such as showing only a subset of available fields, modifying their order, or grouping them into rows. For example, you could define a simpler version of the admin form for the django.contrib.flatpages.models.FlatPage model as follows:
In the above example, only the fields url, title and content will be displayed, sequentially, in the form. fields can contain values defined in ModelAdmin.readonly_fields to be displayed as read-only.
For more complex layout needs, see the fieldsets option.
The fields option accepts the same types of values as list_display, except that callables aren’t accepted. Names of model and model admin methods will only be used if they’re listed in readonly_fields.
To display multiple fields on the same line, wrap those fields in their own tuple. In this example, the url and title fields will display on the same line and the content field will be displayed below them on its own line:
Note
This fields option should not be confused with the fields dictionary key that is within the fieldsets option, as described in the next section.
If neither fields nor fieldsets options are present, Django will default to displaying each field that isn’t an AutoField and has editable=True, in a single fieldset, in the same order as the fields are defined in the model.


Set fieldsets to control the layout of admin “add” and “change” pages.
fieldsets is a list of two-tuples, in which each two-tuple represents a <fieldset> on the admin form page. (A <fieldset> is a “section” of the form.)
The two-tuples are in the format (name, field_options), where name is a string representing the title of the fieldset and field_options is a dictionary of information about the fieldset, including a list of fields to be displayed in it.
A full example, taken from the django.contrib.flatpages.models.FlatPage model:
This results in an admin page that looks like:
If neither fieldsets nor fields options are present, Django will default to displaying each field that isn’t an AutoField and has editable=True, in a single fieldset, in the same order as the fields are defined in the model.
The field_options dictionary can have the following keys:
A tuple of field names to display in this fieldset. This key is required.
Example:
As with the fields option, to display multiple fields on the same line, wrap those fields in their own tuple. In this example, the first_name and last_name fields will display on the same line:
fields can contain values defined in readonly_fields to be displayed as read-only.
If you add the name of a callable to fields, the same rule applies as with the fields option: the callable must be listed in readonly_fields.
A list or tuple containing extra CSS classes to apply to the fieldset.
Example:
Two useful classes defined by the default admin site stylesheet are collapse and wide. Fieldsets with the collapse style will be initially collapsed in the admin and replaced with a small “click to expand” link. Fieldsets with the wide style will be given extra horizontal space.
A string of optional extra text to be displayed at the top of each fieldset, under the heading of the fieldset. This string is not rendered for TabularInline due to its layout.
Note that this value is not HTML-escaped when it’s displayed in the admin interface. This lets you include HTML if you so desire. Alternatively you can use plain text and django.utils.html.escape() to escape any HTML special characters.


By default, a ManyToManyField is displayed in the admin site with a <select multiple>. However, multiple-select boxes can be difficult to use when selecting many items. Adding a ManyToManyField to this list will instead use a nifty unobtrusive JavaScript “filter” interface that allows searching within the options. The unselected and selected options appear in two boxes side by side. See filter_vertical to use a vertical interface.


Same as filter_horizontal, but uses a vertical display of the filter interface with the box of unselected options appearing above the box of selected options.


By default a ModelForm is dynamically created for your model. It is used to create the form presented on both the add/change pages. You can easily provide your own ModelForm to override any default form behavior on the add/change pages. Alternatively, you can customize the default form rather than specifying an entirely new one by using the ModelAdmin.get_form() method.
For an example see the section Adding custom validation to the admin.
Note
If you define the Meta.model attribute on a ModelForm, you must also define the Meta.fields attribute (or the Meta.exclude attribute). However, since the admin has its own way of defining fields, the Meta.fields attribute will be ignored.
If the ModelForm is only going to be used for the admin, the easiest solution is to omit the Meta.model attribute, since ModelAdmin will provide the correct model to use. Alternatively, you can set fields = [] in the Meta class to satisfy the validation on the ModelForm.
Note
If your ModelForm and ModelAdmin both define an exclude option then ModelAdmin takes precedence:
In the above example, the “age” field will be excluded but the “name” field will be included in the generated form.


Like the formfield_for_foreignkey and formfield_for_manytomany methods, the formfield_for_choice_field method can be overridden to change the default formfield for a field that has declared choices. For example, if the choices available to a superuser should be different than those available to regular staff, you could proceed as follows:
Note
Any choices attribute set on the formfield will be limited to the form field only. If the corresponding field on the model has choices set, the choices provided to the form must be a valid subset of those choices, otherwise the form submission will fail with a ValidationError when the model itself is validated before saving.


The formfield_for_foreignkey method on a ModelAdmin allows you to override the default formfield for a foreign keys field. For example, to return a subset of objects for this foreign key field based on the user:
This uses the HttpRequest instance to filter the Car foreign key field to only display the cars owned by the User instance.
For more complex filters, you can use ModelForm.__init__() method to filter based on an instance of your model (see Fields which handle relationships). For example:


Like the formfield_for_foreignkey method, the formfield_for_manytomany method can be overridden to change the default formfield for a many to many field. For example, if an owner can own multiple cars and cars can belong to multiple owners – a many to many relationship – you could filter the Car foreign key field to only display the cars owned by the User:


This provides a quick-and-dirty way to override some of the Field options for use in the admin. formfield_overrides is a dictionary mapping a field class to a dict of arguments to pass to the field at construction time.
Since that’s a bit abstract, let’s look at a concrete example. The most common use of formfield_overrides is to add a custom widget for a certain type of field. So, imagine we’ve written a RichTextEditorWidget that we’d like to use for large text fields instead of the default <textarea>. Here’s how we’d do that:
Note that the key in the dictionary is the actual field class, not a string. The value is another dictionary; these arguments will be passed to the form field’s __init__() method. See The Forms API for details.
Warning
If you want to use a custom widget with a relation field (i.e. ForeignKey or ManyToManyField), make sure you haven’t included that field’s name in raw_id_fields, radio_fields, or autocomplete_fields.
formfield_overrides won’t let you change the widget on relation fields that have raw_id_fields, radio_fields, or autocomplete_fields set. That’s because raw_id_fields, radio_fields, and autocomplete_fields imply custom widgets of their own.


Finally, you can conditionally enable or disable actions on a per-request (and hence per-user basis) by overriding ModelAdmin.get_actions().
This returns a dictionary of actions allowed. The keys are action names, and the values are (function, name, short_description) tuples.
For example, if you only want users whose names begin with ‘J’ to be able to delete objects in bulk:


The get_autocomplete_fields() method is given the HttpRequest and is expected to return a list or tuple of field names that will be displayed with an autocomplete widget as described above in the ModelAdmin.autocomplete_fields section.


A hook for the initial data on admin change forms. By default, fields are given initial values from GET parameters. For instance, ?name=initial_value will set the name field’s initial value to be initial_value.
This method should return a dictionary in the form {'fieldname': 'fieldval'}:


Returns the Changelist class to be used for listing. By default, django.contrib.admin.views.main.ChangeList is used. By inheriting this class you can change the behavior of the listing.


Returns a ModelForm class for use in the Formset on the changelist page. To use a custom form, for example:
Note
If you define the Meta.model attribute on a ModelForm, you must also define the Meta.fields attribute (or the Meta.exclude attribute). However, ModelAdmin ignores this value, overriding it with the ModelAdmin.list_editable attribute. The easiest solution is to omit the Meta.model attribute, since ModelAdmin will provide the correct model to use.


Returns a ModelFormSet class for use on the changelist page if list_editable is used. To use a custom formset, for example:


A hook for customizing the deletion process of the delete_view() and the “delete selected” action.
The objs argument is a homogeneous iterable of objects (a QuerySet or a list of model instances) to be deleted, and request is the HttpRequest.
This method must return a 4-tuple of (deleted_objects, model_count, perms_needed, protected).
deleted_objects is a list of strings representing all the objects that will be deleted. If there are any related objects to be deleted, the list is nested and includes those related objects. The list is formatted in the template using the unordered_list filter.
model_count is a dictionary mapping each model’s verbose_name_plural to the number of objects that will be deleted.
perms_needed is a set of verbose_names of the models that the user doesn’t have permission to delete.
protected is a list of strings representing of all the protected related objects that can’t be deleted. The list is displayed in the template.


The get_exclude method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list of fields, as described in ModelAdmin.exclude.


The get_fields method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list of fields, as described above in the ModelAdmin.fields section.


The get_fieldsets method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list of two-tuples, in which each two-tuple represents a <fieldset> on the admin form page, as described above in the ModelAdmin.fieldsets section.


Returns a ModelForm class for use in the admin add and change views, see add_view() and change_view().
The base implementation uses modelform_factory() to subclass form, modified by attributes such as fields and exclude. So, for example, if you wanted to offer additional fields to superusers, you could swap in a different base form like so:
You may also return a custom ModelForm class directly.


A hook for customizing the keyword arguments passed to the constructor of a formset. For example, to pass request to formset forms:
You can also used it to set initial for formset forms.


Yields (FormSet, InlineModelAdmin) pairs for use in admin add and change views.
For example if you wanted to display a particular inline only in the change view, you could override get_formsets_with_inlines as follows: