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


The address of the client sending the request.


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


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


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


Called to get a stream for the file upload.
This must provide a file-like class with read(), readline() and seek() methods that is both writeable and readable.
The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters.
BinaryIO


A cache control for requests. This is immutable and gives access to all the request-relevant cache control headers.
To get a header of the RequestCacheControl object again you can convert the object into a string or call the to_header() method. If you plan to subclass it and add your own items have a look at the sourcecode for that class.
New in version 0.5: In previous versions a CacheControl class existed that was used both for request and response.
accessor for ‘no-cache’
accessor for ‘no-store’
accessor for ‘max-age’
accessor for ‘no-transform’
accessor for ‘max-stale’
accessor for ‘min-fresh’
accessor for ‘only-if-cached’


Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application.
Example:
f (Callable[[...], WSGIApplication]) –
WSGIApplication


Represents an outgoing WSGI HTTP response with body, status, and headers. Has properties and methods for using the functionality defined by various HTTP specs.
The response body is flexible to support different use cases. The simple form is passing bytes, or a string which will be encoded as UTF-8. Passing an iterable of bytes or strings makes this a streaming response. A generator is particularly useful for building a CSV file in memory or using SSE (Server Sent Events). A file-like object is also iterable, although the send_file() helper should be used in that case.
The response object is itself a WSGI application callable. When called (__call__()) with environ and start_response, it will pass its status and headers to start_response then return its body as an iterable.
None
Changed in version 2.0: Combine BaseResponse and mixins into a single Response class. Using the old classes is deprecated and will be removed in Werkzeug 2.1.
Changed in version 0.5: The direct_passthrough parameter was added.
Process this response as WSGI application.
an application iterator
Iterable[bytes]
This method can be called by methods that need a sequence. If mutable is true, it will also ensure that the response sequence is a standard Python list.
New in version 0.6.
mutable (bool) –
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.
Should this response object correct the location header to be RFC conformant? This is true by default.
New in version 0.8.
Should this response object automatically set the content-length header if possible? This is true by default.
New in version 0.8.
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]]]
if set to False accessing properties on the response object will not try to consume the response iterator and convert it into a list.
New in version 0.6.2: That attribute was previously called implicit_seqence_conversion. (Notice the typo). If you did use this feature, you have to adapt your code to the name change.
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.
A module or other object that has dumps and loads functions that match the API of the built-in json module.
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
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 response body to send as the WSGI iterable. A list of strings or bytes represents a fixed-length response, any other iterable is a streaming response. Strings are encoded to bytes as UTF-8.
Do not set to a plain string or bytes, that will cause sending the response to be very inefficient as it will iterate one byte at a time.
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.


Should this response object correct the location header to be RFC conformant? This is true by default.
New in version 0.8.


Should this response object automatically set the content-length header if possible? This is true by default.
New in version 0.8.


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


if set to False accessing properties on the response object will not try to consume the response iterator and convert it into a list.
New in version 0.6.2: That attribute was previously called implicit_seqence_conversion. (Notice the typo). If you did use this feature, you have to adapt your code to the name change.


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]


A module or other object that has dumps and loads functions that match the API of the built-in json module.


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


The response body to send as the WSGI iterable. A list of strings or bytes represents a fixed-length response, any other iterable is a streaming response. Strings are encoded to bytes as UTF-8.
Do not set to a plain string or bytes, that will cause sending the response to be very inefficient as it will iterate one byte at a time.


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


This method can be called by methods that need a sequence. If mutable is true, it will also ensure that the response sequence is a standard Python list.
New in version 0.6.
mutable (bool) –
None


Process this response as WSGI application.
an application iterator
Iterable[bytes]


A cache control for responses. Unlike RequestCacheControl this is mutable and gives access to response-relevant cache control headers.
To get a header of the ResponseCacheControl object again you can convert the object into a string or call the to_header() method. If you plan to subclass it and add your own items have a look at the sourcecode for that class.
New in version 0.5: In previous versions a CacheControl class existed that was used both for request and response.
accessor for ‘no-cache’
accessor for ‘no-store’
accessor for ‘max-age’
accessor for ‘no-transform’
accessor for ‘immutable’
accessor for ‘must-revalidate’
accessor for ‘private’
accessor for ‘proxy-revalidate’
accessor for ‘public’
accessor for ‘s-maxage’


A Rule represents one URL pattern. There are some options for Rule that change the way it behaves and are passed to the Rule constructor. Note that besides the rule-string all arguments must be keyword arguments in order to not break the application on Werkzeug upgrades.
Rule strings basically are just normal URL paths with placeholders in the format <converter(arguments):name> where the converter and the arguments are optional. If no converter is defined the default converter is used which means string in the normal configuration.
URL rules that end with a slash are branch URLs, others are leaves. If you have strict_slashes enabled (which is the default), all branch URLs that are matched without a trailing slash will trigger a redirect to the same URL with the missing slash appended.
The converters are defined on the Map.
The endpoint for this rule. This can be anything. A reference to a function, a string, a number etc. The preferred way is using a string because the endpoint is used for URL generation.
An optional dict with defaults for other rules with the same endpoint. This is a bit tricky but useful if you want to have unique URLs:
If a user now visits http://example.com/all/page/1 he will be redirected to http://example.com/all/. If redirect_defaults is disabled on the Map instance this will only affect the URL generation.
The subdomain rule string for this rule. If not specified the rule only matches for the default_subdomain of the map. If the map is not bound to a subdomain this feature is disabled.
Can be useful if you want to have user profiles on different subdomains and all subdomains are forwarded to your application:
A sequence of http methods this rule applies to. If not specified, all methods are allowed. For example this can be useful if you want different endpoints for POST and GET. If methods are defined and the path matches but the method matched against is not in this list or in the list of another rule for that path the error raised is of the type MethodNotAllowed rather than NotFound. If GET is present in the list of methods and HEAD is not, HEAD is added automatically.
Override the Map setting for strict_slashes only for this rule. If not specified the Map setting is used.
Override Map.merge_slashes for this rule.
Set this to True and the rule will never match but will create a URL that can be build. This is useful if you have resources on a subdomain or folder that are not handled by the WSGI application (like static data)
If given this must be either a string or callable. In case of a callable it’s called with the url adapter that triggered the match and the values of the URL as keyword arguments and has to return the target for the redirect, otherwise it has to be a string with placeholders in rule syntax:
When the rule is matched the routing system will raise a RequestRedirect exception with the target for the redirect.
Keep in mind that the URL will be joined against the URL root of the script so don’t use a leading slash on the target URL unless you really mean root of that domain.
If enabled this rule serves as an alias for another rule with the same endpoint and arguments.
If provided and the URL map has host matching enabled this can be used to provide a match rule for the whole host. This also means that the subdomain feature is disabled.
If True, this rule is only matches for WebSocket (ws://, wss://) requests. By default, rules will only match for HTTP requests.
New in version 1.0: Added websocket.
New in version 1.0: Added merge_slashes.
New in version 0.7: Added alias and host.
Changed in version 0.6.1: HEAD is added to methods if GET is present.
None
Return an unbound copy of this rule.
This can be useful if want to reuse an already bound URL for another map. See get_empty_kwargs to override what keyword arguments are provided to the new copy.
werkzeug.routing.Rule


Return an unbound copy of this rule.
This can be useful if want to reuse an already bound URL for another map. See get_empty_kwargs to override what keyword arguments are provided to the new copy.
werkzeug.routing.Rule


As soon as you have more complex URL setups it’s a good idea to use rule factories to avoid repetitive tasks. Some of them are builtin, others can be added by subclassing RuleFactory and overriding get_rules.
Subclasses of RuleFactory have to override this method and return an iterable of rules.
map (werkzeug.routing.Map) –
Iterable[werkzeug.routing.Rule]


Subclasses of RuleFactory have to override this method and return an iterable of rules.
map (werkzeug.routing.Map) –
Iterable[werkzeug.routing.Rule]


Returns copies of the rules wrapped and expands string templates in the endpoint, rule, defaults or subdomain sections.
Here a small example for such a rule template:
When a rule template is called the keyword arguments are used to replace the placeholders in all the string parameters.
rules (Iterable[Rule]) –
None


Start a WSGI application. Optional features include a reloader, multithreading and fork support.
This function has a command-line interface too:
Changed in version 2.0: Added exclude_patterns parameter.
Changed in version 0.15: Bind to a Unix socket by passing a path that starts with unix:// as the hostname.
New in version 0.10: Improved the reloader and added support for changing the backend through the reloader_type parameter. See Reloader for more information.
New in version 0.9: Added command-line interface.
New in version 0.8: Added support for automatically loading a SSL context from certificate file and private key.
New in version 0.6: support for SSL was added.
New in version 0.5: static_files was added to simplify serving of static files as well as passthrough_errors.
None


Return a tuple in the form (app_iter, status, headers) of the application output. This works best if you pass it an application that returns an iterator 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.
If passed an invalid WSGI application the behavior of this function is undefined. Never pass non-conforming WSGI applications to this function.
tuple in the form (app_iter, status, headers)
Tuple[Iterable[bytes], str, werkzeug.datastructures.Headers]


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


This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance.
Returns True if the two strings are equal, or False if they are not.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use hmac.compare_digest() instead.
New in version 0.7.
bool


Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to os.path.join(). The filename returned is an ASCII only string for maximum portability.
On windows systems the function also makes sure that the file is not named after one of the special device files.
The function might return an empty filename. It’s your responsibility to ensure that the filename is unique and that you abort or generate a random filename if the function returned an empty one.
New in version 0.5.
filename (str) – the filename to secure
str


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.
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, use_x_sendfile=True will tell the server to send the given path, which is much more efficient than reading it in Python.
Response
New in version 2.0: Adapted from Flask’s implementation.
Changed in version 2.0: download_name replaces Flask’s attachment_filename parameter. If as_attachment=False, it is passed with Content-Disposition: inline instead.
Changed in version 2.0: max_age replaces Flask’s cache_timeout parameter. conditional is enabled and max_age is not set by default.
Changed in version 2.0: etag replaces Flask’s add_etags parameter. It can be a string to use instead of generating one.
Changed in version 2.0: If an encoding is returned when guessing mimetype from download_name, set the Content-Encoding header.


A WSGI middleware which provides static content for development environments or simple server setups. Its usage is quite simple:
The contents of the folder ./shared will now be available on http://example.com/shared/. This is pretty useful during development because a standalone media server is not required. Files can also be mounted on the root folder and still continue to use the application because the shared data middleware forwards all unhandled requests to the application, even if the requests are below one of the shared folders.
If pkg_resources is available you can also tell the middleware to serve files from package data:
This will then serve the static folder in the myapplication Python package.
The optional disallow parameter can be a list of fnmatch() rules for files that are not accessible from the web. If cache is set to False no caching headers are sent.
Currently the middleware does not support non-ASCII filenames. If the encoding on the file system happens to match the encoding of the URI it may work but this could also be by accident. We strongly suggest using ASCII only file names for static files.
The middleware will guess the mimetype using the Python mimetype module. If it’s unable to figure out the charset it will fall back to fallback_mimetype.
None
Changed in version 1.0: The default fallback_mimetype is application/octet-stream. If a filename looks like a text mimetype, the utf-8 charset is added to it.
New in version 0.6: Added fallback_mimetype.
Changed in version 0.5: Added cache_timeout.
Subclasses can override this method to disallow the access to certain files. However by providing disallow in the constructor this method is overwritten.
filename (str) –
bool


Subclasses can override this method to disallow the access to certain files. However by providing disallow in the constructor this method is overwritten.
filename (str) –
bool


All URLs provided by this factory have the subdomain set to a specific domain. For example if you want to use the subdomain for the current language this can be a good setup:
All the rules except for the '#select_language' endpoint will now listen on a two letter long subdomain that holds the language code for the current request.
None


Like Subdomain but prefixes the URL rule with a given string:
Now the rule 'blog/show' matches /blog/entry/<entry_slug>.
None


Response subclass that provides extra information about requests made with the test Client.
Test client requests will always return an instance of this class. If a custom response class is passed to the client, it is subclassed along with this to support test information.
If the test request included large files, or if the application is serving a file, call close() to close any open files and prevent Python showing a ResourceWarning.
None
A request object with the environ used to make the request that resulted in this response.
A list of intermediate responses. Populated when the test request is made with follow_redirects enabled.


A list of intermediate responses. Populated when the test request is made with follow_redirects enabled.


A request object with the environ used to make the request that resulted in this response.


Simple test application that dumps the environment. You can use it to check if Werkzeug is working properly:
The application displays important information from the WSGI environment, the Python interpreter and the installed libraries.
Iterable[bytes]


Works like a regular dict but the get() method can perform type conversions. MultiDict and CombinedMultiDict are subclasses of this class and provide the same feature.
New in version 0.5.
Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found:


Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found:


The reverse of escape(). This unescapes all the HTML entities, not only those inserted by escape.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use MarkupSafe instead.
s (str) –
str


Werkzeug uses strings internally everwhere text data is assumed, even if the HTTP standard is not Unicode aware. Basically all incoming data is decoded from the charset (UTF-8 by default) so that you don’t work with bytes directly. Outgoing data is encoded into the target charset.
Imagine you have the German Umlaut ö. In ASCII you cannot represent that character, but in the latin-1 and utf-8 character sets you can represent it, but they look different when encoded:
An ö looks different depending on the encoding which makes it hard to work with it as bytes. Instead, Python treats strings as Unicode text and stores the information LATIN SMALL LETTER O WITH DIAERESIS instead of the bytes for ö in a specific encoding. The length of a string with 1 character will be 1, where the length of the bytes might be some other value.
However, the HTTP spec was written in a time where ASCII bytes were the common way data was represented. To work around this for the modern web, Werkzeug decodes and encodes incoming and outgoing data automatically. Data sent from the browser to the web application is decoded from UTF-8 bytes into a string. Data sent from the application back to the browser is encoded back to UTF-8.
Functions that do internal encoding or decoding accept an errors keyword argument that is passed to str.decode() and str.encode(). The default is 'replace' so that errors are easy to spot. It might be useful to set it to 'strict' in order to catch the error and report the bad data to the client.
In most cases, you should stick with Werkzeug’s default encoding of UTF-8. If you have a specific reason to, you can subclass wrappers.Request and wrappers.Response to change the encoding and error handling.
The error handling can only be changed for the request. Werkzeug will always raise errors when encoding to bytes in the response. It’s your responsibility to not create data that is not present in the target charset. This is not an issue for UTF-8.


This converter is the default converter and accepts any string but only one path segment. Thus the string can not include a slash.
This is the default validator.
Example:
None


Unquote a single etag:
etag (Optional[str]) – the etag identifier to unquote.
a (etag, weak) tuple.
Union[Tuple[str, bool], Tuple[None, None]]


Unquotes a header value. (Reversal of quote_header_value()). This does not use the real unquoting but what browsers are actually using for quoting.
New in version 0.5.
str


Convert a URI to an IRI. All valid UTF-8 characters are unquoted, leaving all reserved and invalid characters quoted. If the URL has a domain, it is decoded from Punycode.
str
Changed in version 0.15: All reserved and invalid characters remain quoted. Previously, only some reserved characters were preserved, and invalid bytes were replaced instead of left quoted.
New in version 0.6.


Represents a parsed URL. This behaves like a regular tuple but also has some extra attributes that give further insight into the URL.
Create new instance of _URLTuple(scheme, netloc, path, query, fragment)
Encodes the URL to a tuple made out of bytes. The charset is only being used for the path, query and fragment.
werkzeug.urls.BytesURL


Encodes the URL to a tuple made out of bytes. The charset is only being used for the path, query and fragment.
werkzeug.urls.BytesURL


Parse a query string and return it as a MultiDict.
ds.MultiDict[str, str]
Changed in version 2.0: The decode_keys parameter is deprecated and will be removed in Werkzeug 2.1.
Changed in version 0.5: In previous versions “;” and “&” could be used for url decoding. Now only “&” is supported. If you want to use “;”, a different separator can be provided.
Changed in version 0.5: The cls parameter was added.


Works like url_decode() but decodes a stream. The behavior of stream and limit follows functions like make_line_iter(). The generator of pairs is directly fed to the cls so you can consume the data while it’s parsed.
ds.MultiDict[str, str]
Changed in version 2.0: The decode_keys and return_iterator parameters are deprecated and will be removed in Werkzeug 2.1.
New in version 0.8.


URL encode a dict/MultiDict. If a value is None it will not appear in the result string. Per default only values are encoded into the target charset strings.
str
Changed in version 2.0: The encode_keys parameter is deprecated and will be removed in Werkzeug 2.1.
Changed in version 0.5: Added the sort, key, and separator parameters.


Like url_encode() but writes the results to a stream object. If the stream is None a generator over all encoded pairs is returned.
None
Changed in version 2.0: The encode_keys parameter is deprecated and will be removed in Werkzeug 2.1.
New in version 0.8.


Sometimes you get an URL by a user that just isn’t a real URL because it contains unsafe characters like ‘ ‘ and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user:
str


Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.
str


Parses a URL from a string into a URL tuple. If the URL is lacking a scheme it can be provided as second argument. Otherwise, it is ignored. Optionally fragments can be stripped from the URL by setting allow_fragments to False.
The inverse of this function is url_unparse().
werkzeug.urls.BaseURL


URL encode a single string with a given encoding.
str
New in version 0.9.2: The unsafe parameter was added.


URL encode a single string with the given encoding and convert whitespace to “+”.
str


The reverse operation to url_parse(). This accepts arbitrary as well as URL tuples and returns a URL as a string.
components (Tuple[str, str, str, str, str]) – the parsed URL as tuple which should be converted into a URL string.
str


URL decode a single string with a given encoding. If the charset is set to None no decoding is performed and raw bytes are returned.
str


URL decode a single string with the given charset and decode “+” to whitespace.
Per default encoding errors are ignored. If you want a different behavior you can set errors to 'replace' or 'strict'.
str


Represents a parsed user agent header value.
The default implementation does no parsing, only the string attribute is set. A subclass may parse the string to set the common attributes or expose other information. Set werkzeug.wrappers.Request.user_agent_class to use a subclass.
string (str) – The header value to parse.
None
New in version 2.0: This replaces the previous useragents module, but does not provide a built-in parser.
The OS name, if it could be parsed from the string.
The browser name, if it could be parsed from the string.
The browser version, if it could be parsed from the string.
The browser language, if it could be parsed from the string.
The original header value.
Convert to a header value.
str


Represents a parsed user agent header value.
This uses a basic parser to try to extract some information from the header.
environ_or_string (t.Union[str, WSGIEnvironment]) – The header value to parse, or a WSGI environ containing the header.
None
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Subclass werkzeug.user_agent.UserAgent (note the new module name) to use a dedicated parser instead.
Changed in version 2.0: Passing a WSGI environ is deprecated and will be removed in 2.1.
Convert to a header value.
str


The browser name, if it could be parsed from the string.


The browser language, if it could be parsed from the string.


The OS name, if it could be parsed from the string.


The browser version, if it could be parsed from the string.


Various utility functions shipped with Werkzeug.
Helper object for HTML generation.
Per default there are two instances of that class. The html one, and the xhtml one for those two dialects. The class uses keyword parameters and positional parameters to generate small snippets of HTML.
Keyword parameters are converted to XML/SGML attributes, positional arguments are used as children. Because Python accepts positional arguments before keyword arguments it’s a good idea to use a list with the star-syntax for some children:
This class works around some browser limitations and can not be used for arbitrary SGML/XML generation. For that purpose lxml and similar libraries exist.
Calling the builder escapes the string passed:
Deprecated since version 2.0: Will be removed in Werkzeug 2.1.
Replace &, <, >, ", and ' with HTML-safe sequences.
None is escaped to an empty string.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use MarkupSafe instead.
s (Any) –
str
The reverse of escape(). This unescapes all the HTML entities, not only those inserted by escape.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use MarkupSafe instead.
s (str) –
str
A property() that is only evaluated once. Subsequent access returns the cached value. Setting the property sets the cached value. Deleting the property clears the cached value, accessing it again will evaluate it again.
The class must have a __dict__ for this to work.
Changed in version 2.0: del obj.name clears the cached value.
None
Invalidates the cache for a cached_property:
You must pass the name of the cached property as the second argument.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use del obj.name instead.
None
Maps request attributes to environment variables. This works not only for the Werkzeug request object, but also any other class with an environ attribute:
If you pass it a second value it’s used as default if the key does not exist, the third one can be a converter that takes a value and converts it. If it raises ValueError or TypeError the default value is used. If no default value is provided None is used.
Per default the property is read only. You have to explicitly enable it by passing read_only=False to the constructor.
Like environ_property but for headers.
Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, 307, and 308. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
New in version 0.10: The class used for the Response object can now be passed in.
New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function.
Response
Redirects to the same URL but with a slash appended. The behavior of this function is undefined if the path ends with a slash already.
Response
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.
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, use_x_sendfile=True will tell the server to send the given path, which is much more efficient than reading it in Python.
Response
New in version 2.0: Adapted from Flask’s implementation.
Changed in version 2.0: download_name replaces Flask’s attachment_filename parameter. If as_attachment=False, it is passed with Content-Disposition: inline instead.
Changed in version 2.0: max_age replaces Flask’s cache_timeout parameter. conditional is enabled and max_age is not set by default.
Changed in version 2.0: etag replaces Flask’s add_etags parameter. It can be a string to use instead of generating one.
Changed in version 2.0: If an encoding is returned when guessing mimetype from download_name, set the Content-Encoding header.
Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (xml.sax.saxutils.escape) or with a colon as object delimiter (xml.sax.saxutils:escape).
If silent is True the return value will be None if the import fails.
imported object
Any
Finds all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application.
Packages are not returned unless include_packages is True. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module.
generator
Iterator[str]
Checks if the function accepts the arguments and keyword arguments. Returns a new (args, kwargs) tuple that can safely be passed to the function without causing a TypeError because the function signature is incompatible. If drop_extra is set to True (which is the default) any extra positional or keyword arguments are dropped automatically.
The exception raised provides three attributes:
A set of argument names that the function expected but where missing.
A dict of keyword arguments that the function can not handle but where provided.
A list of values that where given by positional argument but the function cannot accept.
This can be useful for decorators that forward user submitted data to a view function:
tuple in the form (args, kwargs).
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use inspect.signature() instead.
Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to os.path.join(). The filename returned is an ASCII only string for maximum portability.
On windows systems the function also makes sure that the file is not named after one of the special device files.
The function might return an empty filename. It’s your responsibility to ensure that the filename is unique and that you abort or generate a random filename if the function returned an empty one.
New in version 0.5.
filename (str) – the filename to secure
str
Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments bind_arguments returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments.
a dict of bound keyword arguments.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use Signature.bind() instead.
Please refer to URL Helpers.
Represents a parsed user agent header value.
The default implementation does no parsing, only the string attribute is set. A subclass may parse the string to set the common attributes or expose other information. Set werkzeug.wrappers.Request.user_agent_class to use a subclass.
string (str) – The header value to parse.
None
New in version 2.0: This replaces the previous useragents module, but does not provide a built-in parser.
The OS name, if it could be parsed from the string.
The browser name, if it could be parsed from the string.
The browser version, if it could be parsed from the string.
The browser language, if it could be parsed from the string.
The original header value.
Convert to a header value.
str
Deprecated since version 2.0: This module will be removed in Werkzeug 2.1. Subclass werkzeug.user_agent.UserAgent to use a dedicated parser instead.
Represents a parsed user agent header value.
This uses a basic parser to try to extract some information from the header.
environ_or_string (t.Union[str, WSGIEnvironment]) – The header value to parse, or a WSGI environ containing the header.
None
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Subclass werkzeug.user_agent.UserAgent (note the new module name) to use a dedicated parser instead.
Changed in version 2.0: Passing a WSGI environ is deprecated and will be removed in 2.1.
Convert to a header value.
str
New in version 0.6.1.
Hash a password with the given method and salt with a string of the given length. The format of the string returned includes the method that was used so that check_password_hash() can check the hash.
The format for the hashed string looks like this:
This method can not generate unsalted passwords but it is possible to set param method=’plain’ in order to enforce plaintext passwords. If a salt is used, hmac is used internally to salt the password.
If PBKDF2 is wanted it can be enabled by setting the method to pbkdf2:method:iterations where iterations is optional:
str
Check a password against a given salted and hashed password value. In order to support unsalted legacy passwords this method supports plain text passwords, md5 and sha1 hashes (both salted and unsalted).
Returns True if the password matched, False otherwise.
bool
This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance.
Returns True if the two strings are equal, or False if they are not.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use hmac.compare_digest() instead.
New in version 0.7.
bool
Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory.
A safe path, otherwise None.
Optional[str]
Like pbkdf2_bin(), but returns a hex-encoded string.
str
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use hashlib.pbkdf2_hmac() instead.
New in version 0.9.
Returns a binary digest for the PBKDF2 hash algorithm of data with the given salt. It iterates iterations times and produces a key of keylen bytes. By default, SHA-256 is used as hash function; a different hashlib hashfunc can be provided.
bytes
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use hashlib.pbkdf2_hmac() instead.
New in version 0.9.
Werkzeug uses standard Python logging. The logger is named "werkzeug".
If the logger level is not set, it will be set to INFO on first use. If there is no handler for that level, a StreamHandler is added.


This converter only accepts UUID strings:
New in version 0.10.
None


Checks if the function accepts the arguments and keyword arguments. Returns a new (args, kwargs) tuple that can safely be passed to the function without causing a TypeError because the function signature is incompatible. If drop_extra is set to True (which is the default) any extra positional or keyword arguments are dropped automatically.
The exception raised provides three attributes:
A set of argument names that the function expected but where missing.
A dict of keyword arguments that the function can not handle but where provided.
A list of values that where given by positional argument but the function cannot accept.
This can be useful for decorators that forward user submitted data to a view function:
tuple in the form (args, kwargs).
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use inspect.signature() instead.


Wraps a file. This uses the WSGI server’s file wrapper if available or otherwise the generic FileWrapper.
New in version 0.5.
If the file wrapper from the WSGI server is used it’s important to not iterate over it from inside the application but to pass it through unchanged. If you want to pass out a file wrapper inside a response object you have to set Response.direct_passthrough to True.
More information about file wrappers are available in PEP 333.
Iterable[bytes]


Provides simple access to WWW-Authenticate headers.
A string indicating a pair of algorithms used to produce the digest and a checksum. If this is not present it is assumed to be “MD5”. If the algorithm is not understood, the challenge should be ignored (and a different one used, if there is more than one).
A static helper function for Authentication subclasses to add extra authentication system properties onto a class:
For more information have a look at the sourcecode to see how the regular properties (realm etc.) are implemented.
A list of URIs that define the protection space. If a URI is an absolute path, it is relative to the canonical root URL of the server being accessed.
A server-specified data string which should be uniquely generated each time a 401 response is made. It is recommended that this string be base64 or hexadecimal data.
A string of data, specified by the server, which should be returned by the client unchanged in the Authorization header of subsequent requests with URIs in the same protection space. It is recommended that this string be base64 or hexadecimal data.
A set of quality-of-privacy directives such as auth and auth-int.
A string to be displayed to users so they know which username and password to use. This string should contain at least the name of the host performing the authentication and might additionally indicate the collection of users who might have access.
Clear the auth info and enable basic auth.
Clear the auth info and enable digest auth.
A flag, indicating that the previous request from the client was rejected because the nonce value was stale.
Convert the stored values into a WWW-Authenticate header.
The type of the auth mechanism. HTTP currently specifies Basic and Digest.


A static helper function for Authentication subclasses to add extra authentication system properties onto a class:
For more information have a look at the sourcecode to see how the regular properties (realm etc.) are implemented.


Clear the auth info and enable basic auth.


Clear the auth info and enable digest auth.


Convert the stored values into a WWW-Authenticate header.


Versioning an interface is just a "polite" way to kill deployed clients.
— Roy Fielding.
API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes.
Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers.
There are a number of valid approaches to approaching versioning. Non-versioned systems can also be appropriate, particularly if you're engineering for very long-term systems with multiple clients outside of your control.
When API versioning is enabled, the request.version attribute will contain a string that corresponds to the version requested in the incoming client request.
By default, versioning is not enabled, and request.version will always return None.
How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example:
The reverse function included by REST framework ties in with the versioning scheme. You need to make sure to include the current request as a keyword argument, like so.
The above function will apply any URL transformations appropriate to the request version. For example:
When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer.
Doing so will allow any returned URLs to include the appropriate versioning.
The versioning scheme is defined by the DEFAULT_VERSIONING_CLASS settings key.
Unless it is explicitly set, the value for DEFAULT_VERSIONING_CLASS will be None. In this case the request.version attribute will always return None.
You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the versioning_class attribute.
The following settings keys are also used to control versioning:
You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the default_version, allowed_versions and version_param class variables. For example, if you want to use URLPathVersioning:
This scheme requires the client to specify the version as part of the media type in the Accept header. The version is included as a media type parameter, that supplements the main media type.
Here's an example HTTP request using the accept header versioning style.
In the example request above request.version attribute would return the string '1.0'.
Versioning based on accept headers is generally considered as best practice, although other styles may be suitable depending on your client requirements.
Strictly speaking the json media type is not specified as including additional parameters. If you are building a well-specified public API you might consider using a vendor media type. To do so, configure your renderers to use a JSON based renderer with a custom media type:
Your client requests would now look like this:
This scheme requires the client to specify the version as part of the URL path.
Your URL conf must include a pattern that matches the version with a 'version' keyword argument, so that this information is available to the versioning scheme.
To the client, this scheme is the same as URLPathVersioning. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.
With this scheme the request.version attribute is determined based on the namespace that matches the incoming request path.
In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace:
Both URLPathVersioning and NamespaceVersioning are reasonable if you just need a simple versioning scheme. The URLPathVersioning approach might be better suitable for small ad-hoc projects, and the NamespaceVersioning is probably easier to manage for larger projects.
The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL.
For example the following is an HTTP request to the http://v1.example.com/bookings/ URL:
By default this implementation expects the hostname to match this simple regular expression:
Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.
The HostNameVersioning scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as 127.0.0.1. There are various online tutorials on how to access localhost with a custom subdomain which you may find helpful in this case.
Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions.
This scheme is a simple style that includes the version as a query parameter in the URL. For example:
To implement a custom versioning scheme, subclass BaseVersioning and override the .determine_version method.
The following example uses a custom X-API-Version header to determine the requested version.
If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the .reverse() method on the class. See the source code for examples.
versioning.py


Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.
— Django documentation
REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types.
The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.
The basic process of content negotiation involves examining the request's Accept header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL http://example.com/api/users_count.json might be an endpoint that always returns JSON data.
For more information see the documentation on content negotiation.
The default set of renderers may be set globally, using the DEFAULT_RENDERER_CLASSES setting. For example, the following settings would use JSON as the main media type and also include the self describing API.
You can also set the renderers used for an individual view, or viewset, using the APIView class-based views.
Or, if you're using the @api_view decorator with function based views.
It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an Accept: */* header, or not including an Accept header at all, then REST framework will select the first renderer in the list to use for the response.
For example if your API serves JSON responses and the HTML browsable API, you might want to make JSONRenderer your default renderer, in order to send JSON responses to clients that do not specify an Accept header.
If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making TemplateHTMLRenderer your default renderer, in order to play nicely with older browsers that send broken accept headers.
Renders the request data into JSON, using utf-8 encoding.
Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace:
The client may additionally include an 'indent' media type parameter, in which case the returned JSON will be indented. For example Accept: application/json; indent=4.
The default JSON encoding style can be altered using the UNICODE_JSON and COMPACT_JSON settings keys.
.media_type: application/json
.format: 'json'
.charset: None
Renders data to HTML, using Django's standard template rendering. Unlike other renderers, the data passed to the Response does not need to be serialized. Also, unlike other renderers, you may want to include a template_name argument when creating the Response.
The TemplateHTMLRenderer will create a RequestContext, using the response.data as the context dict, and determine a template name to use to render the context.
Note: When used with a view that makes use of a serializer the Response sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
The template name is determined by (in order of preference):
An example of a view that uses TemplateHTMLRenderer:
You can use TemplateHTMLRenderer either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
If you're building websites that use TemplateHTMLRenderer along with other renderer classes, you should consider listing TemplateHTMLRenderer as the first class in the renderer_classes list, so that it will be prioritised first even for browsers that send poorly formed ACCEPT: headers.
See the HTML & Forms Topic Page for further examples of TemplateHTMLRenderer usage.
.media_type: text/html
.format: 'html'
.charset: utf-8
See also: StaticHTMLRenderer
A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.
An example of a view that uses StaticHTMLRenderer:
You can use StaticHTMLRenderer either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
.media_type: text/html
.format: 'html'
.charset: utf-8
See also: TemplateHTMLRenderer
Renders data into HTML for the Browsable API:
This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.
.media_type: text/html
.format: 'api'
.charset: utf-8
.template: 'rest_framework/api.html'
By default the response content will be rendered with the highest priority renderer apart from BrowsableAPIRenderer. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the get_default_renderer() method. For example:
Renders data into HTML for an admin-like display:
This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data.
Note that views that have nested or list serializers for their input won't work well with the AdminRenderer, as the HTML forms are unable to properly support them.
Note: The AdminRenderer is only able to include links to detail pages when a properly configured URL_FIELD_NAME (url by default) attribute is present in the data. For HyperlinkedModelSerializer this will be the case, but for ModelSerializer or plain Serializer classes you'll need to make sure to include the field explicitly. For example here we use models get_absolute_url method:
.media_type: text/html
.format: 'admin'
.charset: utf-8
.template: 'rest_framework/admin.html'
Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing <form> tags, a hidden CSRF input or any submit buttons.
This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the render_form template tag.
For more information see the HTML & Forms documentation.
.media_type: text/html
.format: 'form'
.charset: utf-8
.template: 'rest_framework/horizontal/form.html'
This renderer is used for rendering HTML multipart form data. It is not suitable as a response renderer, but is instead used for creating test requests, using REST framework's test client and test request factory.
.media_type: multipart/form-data; boundary=BoUnDaRyStRiNg
.format: 'multipart'
.charset: utf-8
To implement a custom renderer, you should override BaseRenderer, set the .media_type and .format properties, and implement the .render(self, data, media_type=None, renderer_context=None) method.
The method should return a bytestring, which will be used as the body of the HTTP response.
The arguments passed to the .render() method are:
The request data, as set by the Response() instantiation.
Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.
Depending on the client's Accept: header, this may be more specific than the renderer's media_type attribute, and may include media type parameters. For example "application/json; nested=true".
Optional. If provided, this is a dictionary of contextual information provided by the view.
By default this will include the following keys: view, request, response, args, kwargs.
The following is an example plaintext renderer that will return a response with the data parameter as the content of the response.
By default renderer classes are assumed to be using the UTF-8 encoding. To use a different encoding, set the charset attribute on the renderer.
Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the Response class, with the charset attribute set on the renderer used to determine the encoding.
If the renderer returns a bytestring representing raw binary content, you should set a charset value of None, which will ensure the Content-Type header of the response will not have a charset value set.
In some cases you may also want to set the render_style attribute to 'binary'. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.
You can do some pretty flexible things using REST framework's renderers. Some examples...
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access request.accepted_renderer to determine the negotiated renderer that will be used for the response.
For example:
In some cases you might want a renderer to serve a range of media types. In this case you can underspecify the media types it should respond to, by using a media_type value such as image/*, or */*.
If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the content_type attribute. For example:
For the purposes of many Web APIs, simple JSON responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and HATEOAS you'll need to consider the design and usage of your media types in more detail.
In the words of Roy Fielding, "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.".
For good examples of custom media types, see GitHub's use of a custom application/vnd.github+json media type, and Mike Amundsen's IANA approved application/vnd.collection+json JSON-based hypermedia.
Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an Http404 or PermissionDenied exception, or a subclass of APIException.
If you're using either the TemplateHTMLRenderer or the StaticHTMLRenderer and an exception is raised, the behavior is slightly different, and mirrors Django's default handling of error views.
Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.
Templates will render with a RequestContext which includes the status_code and details keys.
Note: If DEBUG=True, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.
The following third party packages are also available.
REST framework YAML provides YAML parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
Install using pip.
Modify your REST framework settings.
REST Framework XML provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
Install using pip.
Modify your REST framework settings.
REST framework JSONP provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package.
Warning: If you require cross-domain AJAX requests, you should generally be using the more modern approach of CORS as an alternative to JSONP. See the CORS documentation for more details.
The jsonp approach is essentially a browser hack, and is only appropriate for globally readable API endpoints, where GET requests are unauthenticated and do not require any user permissions.
Install using pip.
Modify your REST framework settings.
MessagePack is a fast, efficient binary serialization format. Juan Riaza maintains the djangorestframework-msgpack package which provides MessagePack renderer and parser support for REST framework.
XLSX is the world's most popular binary spreadsheet format. Tim Allen of The Wharton School maintains drf-renderer-xlsx, which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
Install using pip.
Modify your REST framework settings.
To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the Content-Disposition header. If no filename is provided, it will default to export.xlsx. For example:
Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. Mjumbe Poe maintains the djangorestframework-csv package which provides CSV renderer support for REST framework.
UltraJSON is an optimized C JSON encoder which can give significantly faster JSON rendering. Adam Mertz maintains drf_ujson2, a fork of the now unmaintained drf-ujson-renderer, which implements JSON rendering using the UJSON package.
djangorestframework-camel-case provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by Vitaly Babiy.
Django REST Pandas provides a serializer and renderers that support additional data processing and output via the Pandas DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both .xls and .xlsx), and a number of other formats. It is maintained by S. Andrew Sheppard as part of the wq Project.
Rest Framework Latex provides a renderer that outputs PDFs using Laulatex. It is maintained by Pebble (S/F Software).
renderers.py


Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.
— Apple Developer Documentation
Together with authentication and throttling, permissions determine whether a request should be granted or denied access.
Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the request.user and request.auth properties to determine if the incoming request should be permitted.
Permissions are used to grant or deny access for different classes of users to different parts of the API.
The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework.
A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the IsAuthenticatedOrReadOnly class in REST framework.
Permissions in REST framework are always defined as a list of permission classes.
Before running the main body of the view each permission in the list is checked. If any permission check fails an exceptions.PermissionDenied or exceptions.NotAuthenticated exception will be raised, and the main body of the view will not run.
When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.
Object level permissions are run by REST framework's generic views when .get_object() is called. As with view level permissions, an exceptions.PermissionDenied exception will be raised if the user is not allowed to act on the given object.
If you're writing your own views and want to enforce object level permissions, or if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object.
This will either raise a PermissionDenied or NotAuthenticated exception, or simply return if the view has the appropriate permissions.
For example:
Note: With the exception of DjangoObjectPermissions, the provided permission classes in rest_framework.permissions do not implement the methods necessary to check object permissions.
If you wish to use the provided permission classes in order to check object permissions, you must subclass them and implement the has_object_permission() method described in the Custom permissions section (below).
For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.
Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view.
Because the get_object() method is not called, object level permissions from the has_object_permission() method are not applied when creating objects. In order to restrict object creation you need to implement the permission check either in your Serializer class or override the perform_create() method of your ViewSet class.
The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting. For example.
If not specified, this setting defaults to allowing unrestricted access:
You can also set the authentication policy on a per-view, or per-viewset basis, using the APIView class-based views.
Or, if you're using the @api_view decorator with function based views.
Note: when you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the settings.py file.
Provided they inherit from rest_framework.permissions.BasePermission, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written:
Note: it supports & (and), | (or) and ~ (not).
The AllowAny permission class will allow unrestricted access, regardless of if the request was authenticated or unauthenticated.
This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.
The IsAuthenticated permission class will deny permission to any unauthenticated user, and allow permission otherwise.
This permission is suitable if you want your API to only be accessible to registered users.
The IsAdminUser permission class will deny permission to any user, unless user.is_staff is True in which case permission will be allowed.
This permission is suitable if you want your API to only be accessible to a subset of trusted administrators.
The IsAuthenticatedOrReadOnly will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; GET, HEAD or OPTIONS.
This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.
This permission class ties into Django's standard django.contrib.auth model permissions. This permission must only be applied to views that have a .queryset property or get_queryset() method. Authorization will only be granted if the user is authenticated and has the relevant model permissions assigned.
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a view model permission for GET requests.
To use custom model permissions, override DjangoModelPermissions and set the .perms_map property. Refer to the source code for details.
Similar to DjangoModelPermissions, but also allows unauthenticated users to have read-only access to the API.
This permission class ties into Django's standard object permissions framework that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as django-guardian.
As with DjangoModelPermissions, this permission must only be applied to views that have a .queryset property or .get_queryset() method. Authorization will only be granted if the user is authenticated and has the relevant per-object permissions and relevant model permissions assigned.
Note that DjangoObjectPermissions does not require the django-guardian package, and should support other object-level backends equally well.
As with DjangoModelPermissions you can use custom model permissions by overriding DjangoObjectPermissions and setting the .perms_map property. Refer to the source code for details.
Note: If you need object level view permissions for GET, HEAD and OPTIONS requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the DjangoObjectPermissionsFilter class provided by the djangorestframework-guardian package. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
To implement a custom permission, override BasePermission and implement either, or both, of the following methods:
The methods should return True if the request should be granted access, and False otherwise.
If you need to test if a request is a read operation or a write operation, you should check the request method against the constant SAFE_METHODS, which is a tuple containing 'GET', 'OPTIONS' and 'HEAD'. For example:
Note: The instance-level has_object_permission method will only be called if the view-level has_permission checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call .check_object_permissions(request, obj). If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising PermissionDenied on failure.)
Custom permissions will raise a PermissionDenied exception if the test fails. To change the error message associated with the exception, implement a message attribute directly on your custom permission. Otherwise the default_detail attribute from PermissionDenied will be used. Similarly, to change the code identifier associated with the exception, implement a code attribute directly on your custom permission - otherwise the default_code attribute from PermissionDenied will be used.
The following is an example of a permission class that checks the incoming request's IP address against a blocklist, and denies the request if the IP has been blocked.
As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:
Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling self.check_object_permissions(request, obj) from the view once you have the object instance. This call will raise an appropriate APIException if any object-level permission checks fail, and will otherwise simply return.
Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details.
REST framework offers three different methods to customize access restrictions on a case-by-case basis. These apply in different scenarios and have different effects and limitations.
The following table lists the access restriction methods and the level of control they offer over which actions.
* A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned.  ** The get_*() methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action.
The following third party packages are also available.
The Django REST - Access Policy package provides a way to define complex access rules in declarative policy classes that are attached to view sets or function-based views. The policies are defined in JSON in a format similar to AWS' Identity & Access Management policies.
The Composed Permissions package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.
The REST Condition package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.
The DRY Rest Permissions package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user.
The Django Rest Framework Roles package makes it easier to parameterize your API over multiple types of users.
The Django REST Framework API Key package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. machines) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.
The Django Rest Framework Role Filters package provides simple filtering over multiple types of roles.
The Django Rest Framework PSQ package is an extension that gives support for having action-based permission_classes, serializer_class, and queryset dependent on permission-based rules.
permissions.py