Request / Response Objects
The request and response objects wrap the WSGI environment or the return value from a WSGI application so that it is another WSGI application (wraps a whole application).
How they Work
Your WSGI application is always passed two arguments. The WSGI “environment” and the WSGI start_response
function that is used to start the response phase. The Request
class wraps the environ
for easier access to request variables (form data, request headers etc.).
The Response
on the other hand is a standard WSGI application that you can create. The simple hello world in Werkzeug looks like this:
from werkzeug.wrappers import Response application = Response('Hello World!')
To make it more useful you can replace it with a function and do some processing:
from werkzeug.wrappers import Request, Response def application(environ, start_response): request = Request(environ) response = Response("Hello %s!" % request.args.get('name', 'World!')) return response(environ, start_response)
Because this is a very common task the Request
object provides a helper for that. The above code can be rewritten like this:
from werkzeug.wrappers import Request, Response @Request.application def application(request): return Response("Hello %s!" % request.args.get('name', 'World!'))
The application
is still a valid WSGI application that accepts the environment and start_response
callable.
Mutability and Reusability of Wrappers
The implementation of the Werkzeug request and response objects are trying to guard you from common pitfalls by disallowing certain things as much as possible. This serves two purposes: high performance and avoiding of pitfalls.
For the request object the following rules apply:
- The request object is immutable. Modifications are not supported by default, you may however replace the immutable attributes with mutable attributes if you need to modify it.
- The request object may be shared in the same thread, but is not thread safe itself. If you need to access it from multiple threads, use locks around calls.
- It’s not possible to pickle the request object.
For the response object the following rules apply:
- The response object is mutable
- The response object can be pickled or copied after
freeze()
was called. - Since Werkzeug 0.6 it’s safe to use the same response object for multiple WSGI responses.
- It’s possible to create copies using
copy.deepcopy
.
Base Wrappers
These objects implement a common set of operations. They are missing fancy addon functionality like user agent parsing or etag handling. These features are available by mixing in various mixin classes or using Request
and Response
.
-
class werkzeug.wrappers.BaseRequest(environ, populate_request=True, shallow=False)
-
Very basic request object. This does not implement advanced stuff like entity tag parsing or cache controls. The request object is created with the WSGI environment as first argument and will add itself to the WSGI environment as
'werkzeug.request'
unless it’s created withpopulate_request
set to False.There are a couple of mixins available that add additional functionality to the request object, there is also a class called
Request
which subclassesBaseRequest
and all the important mixins.It’s a good idea to create a custom subclass of the
BaseRequest
and add missing functionality either via mixins or direct implementation. Here an example for such subclasses:from werkzeug.wrappers import BaseRequest, ETagRequestMixin class Request(BaseRequest, ETagRequestMixin): pass
Request objects are read only. As of 0.5 modifications are not allowed in any place. Unlike the lower level parsing functions the request object will use immutable objects everywhere possible.
Per default the request object will assume all the text data is
utf-8
encoded. Please refer to the unicode chapter for more details about customizing the behavior.Per default the request object will be added to the WSGI environment as
werkzeug.request
to support the debugging system. If you don’t want that, setpopulate_request
toFalse
.If
shallow
isTrue
the environment is initialized as shallow object around the environ. Every operation that would modify the environ in any way (such as consuming form data) raises an exception unless theshallow
attribute is explicitly set toFalse
. This is useful for middlewares where you don’t want to consume the form data by accident. A shallow request is not populated to the WSGI environment.Changelog
Changed in version 0.5: read-only mode was enforced by using immutables classes for all data.
-
environ
-
The WSGI environment that the request object uses for data retrival.
-
shallow
-
True
if this request object is shallow (does not modifyenviron
),False
otherwise.
-
_get_file_stream(total_content_length, content_type, filename=None, content_length=None)
-
Called to get a stream for the file upload.
This must provide a file-like class with
read()
,readline()
andseek()
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.
Parameters: - total_content_length – the total content length of all the data in the request combined. This value is guaranteed to be there.
- content_type – the mimetype of the uploaded file.
-
filename – the filename of the uploaded file. May be
None
. - content_length – the length of this file. This value is usually not provided because webbrowsers do not provide this value.
-
access_route
-
If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server.
-
classmethod application(f)
-
Decorate a function as responder that accepts the request as the last argument. This works like the
responder()
decorator but the function is passed the request object as the last argument and the request object will be closed automatically:@Request.application def my_wsgi_app(request): return Response('Hello World!')
As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing.
Parameters: f – the WSGI callable to decorate Returns: a new WSGI callable
-
args
-
The parsed URL parameters (the part in the URL after the question mark).
By default an
ImmutableMultiDict
is returned from this function. This can be changed by settingparameter_storage_class
to a different type. This might be necessary if the order of the form data is important.
-
base_url
-
Like
url
but without the querystring See also:trusted_hosts
.
-
charset = 'utf-8'
-
the charset for the request, defaults to utf-8
-
close()
-
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it.
Changelog
New in version 0.9.
-
A
dict
with the contents of all cookies transmitted with the request.
-
data
-
Contains the incoming request data as string in case it came with a mimetype Werkzeug does not handle.
-
dict_storage_class
-
disable_data_descriptor = False
-
Indicates whether the data descriptor should be allowed to read and buffer up the input stream. By default it’s enabled.
Changelog
New in version 0.9.
-
encoding_errors = 'replace'
-
the error handling procedure for errors, defaults to ‘replace’
-
files
-
MultiDict
object containing all uploaded files. Each key infiles
is the name from the<input type="file" name="">
. Each value infiles
is a WerkzeugFileStorage
object.It basically behaves like a standard file object you know from Python, with the difference that it also has a
save()
function that can store the file on the filesystem.Note that
files
will only contain data if the request method was POST, PUT or PATCH and the<form>
that posted to the request hadenctype="multipart/form-data"
. It will be empty otherwise.See the
MultiDict
/FileStorage
documentation for more details about the used data structure.
-
form
-
The form parameters. By default an
ImmutableMultiDict
is returned from this function. This can be changed by settingparameter_storage_class
to a different type. This might be necessary if the order of the form data is important.Please keep in mind that file uploads will not end up here, but instead in the
files
attribute.Changelog
Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests.
-
form_data_parser_class
-
alias of
werkzeug.formparser.FormDataParser
-
classmethod from_values(*args, **kwargs)
-
Create a new request object based on the values provided. If environ is given missing values are filled from there. This method is useful for small scripts when you need to simulate a request from an URL. Do not use this method for unittesting, there is a full featured client object (
Client
) that allows to create multipart requests, support for cookies etc.This accepts the same options as the
EnvironBuilder
.Changelog
Changed in version 0.5: This method now accepts the same arguments as
EnvironBuilder
. Because of this theenviron
parameter is now calledenviron_overrides
.Returns: request object
-
full_path
-
Requested path as unicode, including the query string.
-
get_data(cache=True, as_text=False, parse_form_data=False)
-
This reads the buffered incoming data from the client into one bytestring. By default this is cached but that behavior can be changed by setting
cache
toFalse
.Usually it’s a bad idea to call this method without checking the content length first as a client could send dozens of megabytes or more to cause memory problems on the server.
Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set
parse_form_data
toTrue
. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory.If
as_text
is set toTrue
the return value will be a decoded unicode string.Changelog
New in version 0.9.
-
headers
-
The headers from the WSGI environ as immutable
EnvironHeaders
.
-
host
-
Just the host including the port if available. See also:
trusted_hosts
.
-
host_url
-
Just the host with scheme as IRI. See also:
trusted_hosts
.
-
is_multiprocess
-
boolean that is
True
if the application is served by a WSGI server that spawns multiple processes.
-
is_multithread
-
boolean that is
True
if the application is served by a multithreaded WSGI server.
-
is_run_once
-
boolean that is
True
if the application will be executed only once in a process lifetime. This is the case for CGI for example, but it’s not guaranteed that the execution only happens one time.
-
is_secure
-
True
if the request is secure.
-
list_storage_class
-
make_form_data_parser()
-
Creates the form data parser. Instantiates the
form_data_parser_class
with some parameters.Changelog
New in version 0.8.
-
max_content_length = None
-
the maximum content length. This is forwarded to the form data parsing function (
parse_form_data()
). When set and theform
orfiles
attribute is accessed and the parsing fails because more than the specified value is transmitted aRequestEntityTooLarge
exception is raised.Have a look at Dealing with Request Data for more details.
Changelog
New in version 0.5.
-
max_form_memory_size = None
-
the maximum form field size. This is forwarded to the form data parsing function (
parse_form_data()
). When set and theform
orfiles
attribute is accessed and the data in memory for post data is longer than the specified value aRequestEntityTooLarge
exception is raised.Have a look at Dealing with Request Data for more details.
Changelog
New in version 0.5.
-
method
-
The request method. (For example
'GET'
or'POST'
).
-
parameter_storage_class
-
path
-
Requested path as unicode. This works a bit like the regular path info in the WSGI environment but will always include a leading slash, even if the URL root is accessed.
-
query_string
-
The URL parameters as raw bytestring.
-
remote_addr
-
The remote address of the client.
-
remote_user
-
If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.
-
scheme
-
URL scheme (http or https).
Changelog
New in version 0.7.
-
script_root
-
The root path of the script without the trailing slash.
-
stream
-
If the incoming form data was not encoded with a known mimetype the data is stored unmodified in this stream for consumption. Most of the time it is a better idea to use
data
which will give you that data as a string. The stream only returns the data once.Unlike
input_stream
this stream is properly guarded that you can’t accidentally read past the length of the input. Werkzeug will internally always refer to this stream to read data which makes it possible to wrap this object with a stream that does filtering.Changelog
Changed in version 0.9: This stream is now always available but might be consumed by the form parser later on. Previously the stream was only set if no parsing happened.
-
trusted_hosts = None
-
Optionally a list of hosts that is trusted by this request. By default all hosts are trusted which means that whatever the client sends the host is will be accepted.
Because
Host
andX-Forwarded-Host
headers can be set to any value by a malicious client, it is recommended to either set this property or implement similar validation in the proxy (if application is being run behind one).Changelog
New in version 0.9.
-
url
-
The reconstructed current URL as IRI. See also:
trusted_hosts
.
-
url_charset
-
The charset that is assumed for URLs. Defaults to the value of
charset
.Changelog
New in version 0.6.
-
url_root
-
The full URL root (with hostname), this is the application root as IRI. See also:
trusted_hosts
.
-
values
-
A
werkzeug.datastructures.CombinedMultiDict
that combinesargs
andform
.
-
want_form_data_parsed
-
Returns True if the request method carries content. As of Werkzeug 0.9 this will be the case if a content type is transmitted.
Changelog
New in version 0.8.
-
-
class werkzeug.wrappers.BaseResponse(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)
-
Base response class. The most important fact about a response object is that it’s a regular WSGI application. It’s initialized with a couple of response parameters (headers, body, status code etc.) and will start a valid WSGI response when called with the environ and start response callable.
Because it’s a WSGI application itself processing usually ends before the actual response is sent to the server. This helps debugging systems because they can catch all the exceptions before responses are started.
Here a small example WSGI application that takes advantage of the response objects:
from werkzeug.wrappers import BaseResponse as Response def index(): return Response('Index page') def application(environ, start_response): path = environ.get('PATH_INFO') or '/' if path == '/': response = index() else: response = Response('Not Found', status=404) return response(environ, start_response)
Like
BaseRequest
which object is lacking a lot of functionality implemented in mixins. This gives you a better control about the actual API of your response objects, so you can create subclasses and add custom functionality. A full featured response object is available asResponse
which implements a couple of useful mixins.To enforce a new type of already existing responses you can use the
force_type()
method. This is useful if you’re working with different subclasses of response objects and you want to post process them with a known interface.Per default the response object will assume all the text data is
utf-8
encoded. Please refer to the unicode chapter for more details about customizing the behavior.Response can be any kind of iterable or string. If it’s a string it’s considered being an iterable with one item which is the string passed. Headers can be a list of tuples or a
Headers
object.Special note for
mimetype
andcontent_type
: For most mime typesmimetype
andcontent_type
work the same, the difference affects only ‘text’ mimetypes. If the mimetype passed withmimetype
is a mimetype starting withtext/
, the charset parameter of the response object is appended to it. In contrast thecontent_type
parameter is always added as header unmodified.Changelog
Changed in version 0.5: the
direct_passthrough
parameter was added.Parameters: - response – a string or response iterable.
- status – a string with a status or an integer with the status code.
-
headers – a list of headers or a
Headers
object. - mimetype – the mimetype for the response. See notice above.
- content_type – the content type for the response. See notice above.
-
direct_passthrough – if set to
True
iter_encoded()
is not called before iteration which makes it possible to pass special iterators through unchanged (seewrap_file()
for more details.)
-
response
-
The application iterator. If constructed from a string this will be a list, otherwise the object provided as application iterator. (The first argument passed to
BaseResponse
)
-
headers
-
A
Headers
object representing the response headers.
-
status_code
-
The response status as integer.
-
direct_passthrough
-
If
direct_passthrough=True
was passed to the response object or if this attribute was set toTrue
before using the response object as WSGI application, the wrapped iterator is returned unchanged. This makes it possible to pass a specialwsgi.file_wrapper
to the response object. Seewrap_file()
for more details.
-
__call__(environ, start_response)
-
Process this response as WSGI application.
Parameters: - environ – the WSGI environment.
- start_response – the response callable provided by the WSGI server.
Returns: an application iterator
-
_ensure_sequence(mutable=False)
-
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.Changelog
New in version 0.6.
-
autocorrect_location_header = True
-
Should this response object correct the location header to be RFC conformant? This is true by default.
Changelog
New in version 0.8.
-
automatically_set_content_length = True
-
Should this response object automatically set the content-length header if possible? This is true by default.
Changelog
New in version 0.8.
-
calculate_content_length()
-
Returns the content length if available or
None
otherwise.
-
call_on_close(func)
-
Adds a function to the internal list of functions that should be called as part of closing down the response. Since 0.7 this function also returns the function that was passed so that this can be used as a decorator.
Changelog
New in version 0.6.
-
charset = 'utf-8'
-
the charset of the response.
-
close()
-
Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.
Changelog
New in version 0.9: Can now be used in a with statement.
-
data
-
A descriptor that calls
get_data()
andset_data()
.
-
default_mimetype = 'text/plain'
-
the default mimetype if none is provided.
-
default_status = 200
-
the default status if none is provided.
-
Delete a cookie. Fails silently if key doesn’t exist.
Parameters: - key – the key (name) of the cookie to be deleted.
- path – if the cookie that should be deleted was limited to a path, the path has to be defined here.
- domain – if the cookie that should be deleted was limited to a domain, that domain has to be defined here.
-
classmethod force_type(response, environ=None)
-
Enforce that the WSGI response is a response object of the current type. Werkzeug will use the
BaseResponse
internally in many situations like the exceptions. If you callget_response()
on an exception you will get back a regularBaseResponse
object, even if you are using a custom subclass.This method can enforce a given response type, and it will also convert arbitrary WSGI callables into response objects if an environ is provided:
# convert a Werkzeug response object into an instance of the # MyResponseClass subclass. response = MyResponseClass.force_type(response) # convert any WSGI application into a response object response = MyResponseClass.force_type(response, environ)
This is especially useful if you want to post-process responses in the main dispatcher and use functionality provided by your subclass.
Keep in mind that this will modify response objects in place if possible!
Parameters: - response – a response object or wsgi application.
- environ – a WSGI environment object.
Returns: a response object.
-
freeze()
-
Call this method if you want to make your response object ready for being pickled. This buffers the generator if there is one. It will also set the
Content-Length
header to the length of the body.Changelog
Changed in version 0.6: The
Content-Length
header is now set.
-
classmethod from_app(app, environ, buffered=False)
-
Create a new response object from an application output. This works best if you pass it an application that returns a generator all the time. Sometimes applications may use the
write()
callable returned by thestart_response
function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should setbuffered
toTrue
which enforces buffering.Parameters: - app – the WSGI application to execute.
- environ – the WSGI environment to execute against.
-
buffered – set to
True
to enforce buffering.
Returns: a response object.
-
get_app_iter(environ)
-
Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response.
If the request method is
HEAD
or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned.Changelog
New in version 0.6.
Parameters: environ – the WSGI environment of the request. Returns: a response iterable.
-
get_data(as_text=False)
-
The string representation of the response body. Whenever you call this property the response iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting
implicit_sequence_conversion
toFalse
.If
as_text
is set toTrue
the return value will be a decoded unicode string.Changelog
New in version 0.9.
-
get_wsgi_headers(environ)
-
This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary.
For example the location header (if present) is joined with the root URL of the environment. Also the content length is automatically set to zero here for certain status codes.
Changelog
Changed in version 0.6: Previously that function was called
fix_headers
and modified the response object in place. Also since 0.6, IRIs in location and content-location headers are handled properly.Also starting with 0.6, Werkzeug will attempt to set the content length if it is able to figure it out on its own. This is the case if all the strings in the response iterable are already encoded and the iterable is buffered.
Parameters: environ – the WSGI environment of the request. Returns: returns a new Headers
object.
-
get_wsgi_response(environ)
-
Returns the final WSGI response as tuple. The first item in the tuple is the application iterator, the second the status and the third the list of headers. The response returned is created specially for the given environment. For example if the request method in the WSGI environment is
'HEAD'
the response will be empty and only the headers and status code will be present.Changelog
New in version 0.6.
Parameters: environ – the WSGI environment of the request. Returns: an (app_iter, status, headers)
tuple.
-
implicit_sequence_conversion = True
-
if set to
False
accessing properties on the response object will not try to consume the response iterator and convert it into a list.Changelog
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.
-
is_sequence
-
If the iterator is buffered, this property will be
True
. A response object will consider an iterator to be buffered if the response attribute is a list or tuple.Changelog
New in version 0.6.
-
is_streamed
-
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 usuallyTrue
if a generator is passed to the response object.This is useful for checking before applying some sort of post filtering that should not take place for streamed responses.
-
iter_encoded()
-
Iter the response encoded with the encoding of the response. If the response object is invoked as WSGI application the return value of this method is used as application iterator unless
direct_passthrough
was activated.
-
make_sequence()
-
Converts the response iterator in a list. By default this happens automatically if required. If
implicit_sequence_conversion
is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items.Changelog
New in version 0.6.
-
Warn if a cookie header exceeds this size. The default, 4093, should be safely supported by most browsers. A cookie larger than this size will still be sent, but it may be ignored or handled incorrectly by some browsers. Set to 0 to disable this check.
Changelog
New in version 0.13.
-
Sets a cookie. The parameters are the same as in the cookie
Morsel
object in the Python standard library but it accepts unicode data, too.A warning is raised if the size of the cookie header exceeds
max_cookie_size
, but the header will still be set.Parameters: - key – the key (name) of the cookie to be set.
- value – the value of the cookie.
-
max_age – should be a number of seconds, or
None
(default) if the cookie should last only as long as the client’s browser session. -
expires – should be a
datetime
object or UNIX timestamp. - path – limits the cookie to a given path, per default it will span the whole domain.
-
domain – if you want to set a cross-domain cookie. For example,
domain=".example.com"
will set a cookie that is readable by the domainwww.example.com
,foo.example.com
etc. Otherwise, a cookie will only be readable by the domain that set it. -
secure – If
True
, the cookie will only be available via HTTPS - httponly – disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers.
- samesite – Limits the scope of the cookie such that it will only be attached to requests if those requests are “same-site”.
-
set_data(value)
-
Sets a new string as response. The value set must be either a unicode or bytestring. If a unicode string is set it’s encoded automatically to the charset of the response (utf-8 by default).
Changelog
New in version 0.9.
-
status
-
The HTTP status code as a string.
-
status_code
-
The HTTP status code as a number.
Mixin Classes
Werkzeug also provides helper mixins for various HTTP related functionality such as etags, cache control, user agents etc. When subclassing you can mix those classes in to extend the functionality of the BaseRequest
or BaseResponse
object. Here a small example for a request object that parses accept headers:
from werkzeug.wrappers import AcceptMixin, BaseRequest class Request(BaseRequest, AcceptMixin): pass
The Request
and Response
classes subclass the BaseRequest
and BaseResponse
classes and implement all the mixins Werkzeug provides:
-
class werkzeug.wrappers.Request(environ, populate_request=True, shallow=False)
-
Full featured request object implementing the following mixins:
-
AcceptMixin
for accept header parsing -
ETagRequestMixin
for etag and cache control handling -
UserAgentMixin
for user agent introspection -
AuthorizationMixin
for http auth handling -
CORSRequestMixin
for Cross Origin Resource Sharing headers -
CommonRequestDescriptorsMixin
for common headers
-
-
class werkzeug.wrappers.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)
-
Full featured response object implementing the following mixins:
-
ETagResponseMixin
for etag and cache control handling -
WWWAuthenticateMixin
for HTTP authentication support -
CORSResponseMixin
for Cross Origin Resource Sharing headers -
ResponseStreamMixin
to add support for thestream
property -
CommonResponseDescriptorsMixin
for various HTTP descriptors
-
Common Descriptors
-
class werkzeug.wrappers.CommonRequestDescriptorsMixin
-
A mixin for
BaseRequest
subclasses. Request objects that mix this class in will automatically get descriptors for a couple of HTTP headers with automatic type conversion.Changelog
New in version 0.5.
-
content_encoding
-
The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.
Changelog
New in version 0.9.
-
content_length
-
The Content-Length entity-header field indicates the size of the entity-body in bytes or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
-
content_md5
-
The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)
Changelog
New in version 0.9.
-
content_type
-
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
-
date
-
The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822.
-
max_forwards
-
The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server.
-
mimetype
-
Like
content_type
, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type istext/HTML; charset=utf-8
the mimetype would be'text/html'
.
-
mimetype_params
-
The mimetype parameters as dict. For example if the content type is
text/html; charset=utf-8
the params would be{'charset': 'utf-8'}
.
-
pragma
-
The Pragma general-header field is used to include implementation-specific directives that might apply to any recipient along the request/response chain. All pragma directives specify optional behavior from the viewpoint of the protocol; however, some systems MAY require that behavior be consistent with the directives.
-
referrer
-
The Referer[sic] request-header field allows the client to specify, for the server’s benefit, the address (URI) of the resource from which the Request-URI was obtained (the “referrer”, although the header field is misspelled).
-
-
class werkzeug.wrappers.CommonResponseDescriptorsMixin
-
A mixin for
BaseResponse
subclasses. Response objects that mix this class in will automatically get descriptors for a couple of HTTP headers with automatic type conversion.-
age
-
The Age response-header field conveys the sender’s estimate of the amount of time since the response (or its revalidation) was generated at the origin server.
Age values are non-negative decimal integers, representing time in seconds.
-
allow
-
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.
-
content_encoding
-
The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.
-
content_language
-
The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body.
-
content_length
-
The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
-
content_location
-
The Content-Location entity-header field MAY be used to supply the resource location for the entity enclosed in the message when that entity is accessible from a location separate from the requested resource’s URI.
-
content_md5
-
The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)
-
content_security_policy
-
The Content-Security-Policy header adds an additional layer of security to help detect and mitigate certain types of attacks.
-
content_security_policy_report_only
-
The Content-Security-Policy-Report-Only header adds a csp policy that is not enforced but is reported thereby helping detect certain types of attacks.
-
content_type
-
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
-
date
-
The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822.
-
expires
-
The Expires entity-header field gives the date/time after which the response is considered stale. A stale cache entry may not normally be returned by a cache.
-
last_modified
-
The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified.
-
location
-
The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource.
-
mimetype
-
The mimetype (content type without charset etc.)
-
mimetype_params
-
The mimetype parameters as dict. For example if the content type is
text/html; charset=utf-8
the params would be{'charset': 'utf-8'}
.Changelog
New in version 0.5.
-
retry_after
-
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.
-
vary
-
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.
-
Response Stream
-
class werkzeug.wrappers.ResponseStreamMixin
-
Mixin for
BaseResponse
subclasses. Classes that inherit from this mixin will automatically get astream
property that provides a write-only interface to the response iterable.-
stream
-
The response iterable as write-only stream.
-
Accept
-
class werkzeug.wrappers.AcceptMixin
-
A mixin for classes with an
environ
attribute to get all the HTTP accept headers asAccept
objects (or subclasses thereof).-
accept_charsets
-
List of charsets this client supports as
CharsetAccept
object.
-
accept_encodings
-
List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at
accept_charset
.
-
accept_languages
-
List of languages this client accepts as
LanguageAccept
object.
-
accept_mimetypes
-
List of mimetypes this client supports as
MIMEAccept
object.
-
Authentication
-
class werkzeug.wrappers.AuthorizationMixin
-
Adds an
authorization
property that represents the parsed value of theAuthorization
header asAuthorization
object.-
The
Authorization
object in parsed form.
-
-
class werkzeug.wrappers.WWWAuthenticateMixin
-
Adds a
www_authenticate
property to a response object.-
www_authenticate
-
The
WWW-Authenticate
header in a parsed form.
-
CORS
-
class werkzeug.wrappers.cors.CORSRequestMixin
-
A mixin for
BaseRequest
subclasses that adds descriptors for Cross Origin Resource Sharing (CORS) headers.New in version 1.0.
-
access_control_request_headers
-
Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set
access_control_allow_headers
on the response to indicate which headers are allowed.
-
access_control_request_method
-
Sent with a preflight request to indicate which method will be used for the cross origin request. Set
access_control_allow_methods
on the response to indicate which methods are allowed.
-
origin
-
The host that the request originated from. Set
access_control_allow_origin
on the response to indicate which origins are allowed.
-
-
class werkzeug.wrappers.cors.CORSResponseMixin
-
A mixin for
BaseResponse
subclasses that adds descriptors for Cross Origin Resource Sharing (CORS) headers.New in version 1.0.
-
access_control_allow_credentials
-
Whether credentials can be shared by the browser to JavaScript code. As part of the preflight request it indicates whether credentials can be used on the cross origin request.
-
access_control_allow_headers
-
Which headers can be sent with the cross origin request.
-
access_control_allow_methods
-
Which methods can be used for the cross origin request.
-
access_control_allow_origin
-
The origin or ‘*’ for any origin that may make cross origin requests.
-
access_control_expose_headers
-
Which headers can be shared by the browser to JavaScript code.
-
access_control_max_age
-
The maximum age in seconds the access control settings can be cached for.
-
ETag
-
class werkzeug.wrappers.ETagRequestMixin
-
Add entity tag and cache descriptors to a request object or object with a WSGI environment available as
environ
. This not only provides access to etags but also to the cache control header.-
cache_control
-
A
RequestCacheControl
object for the incoming cache control headers.
-
if_match
-
An object containing all the etags in the
If-Match
header.Return type: ETags
-
if_modified_since
-
The parsed
If-Modified-Since
header as datetime object.
-
if_none_match
-
An object containing all the etags in the
If-None-Match
header.Return type: ETags
-
if_range
-
The parsed
If-Range
header.Changelog
New in version 0.7.
Return type: IfRange
-
if_unmodified_since
-
The parsed
If-Unmodified-Since
header as datetime object.
-
range
-
The parsed
Range
header.Changelog
New in version 0.7.
Return type: Range
-
-
class werkzeug.wrappers.ETagResponseMixin
-
Adds extra functionality to a response object for etag and cache handling. This mixin requires an object with at least a
headers
object that implements a dict like interface similar toHeaders
.If you want the
freeze()
method to automatically add an etag, you have to mixin this method before the response base class. The default response class does not do that.-
accept_ranges
-
The
Accept-Ranges
header. Even though the name would indicate that multiple values are supported, it must be one string token only.The values
'bytes'
and'none'
are common.Changelog
New in version 0.7.
-
add_etag(overwrite=False, weak=False)
-
Add an etag for the current response if there is none yet.
-
cache_control
-
The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.
-
content_range
-
The
Content-Range
header as aContentRange
object. Available even if the header is not set.Changelog
New in version 0.7.
-
freeze(no_etag=False)
-
Call this method if you want to make your response object ready for pickeling. This buffers the generator if there is one. This also sets the etag unless
no_etag
is set toTrue
.
-
get_etag()
-
Return a tuple in the form
(etag, is_weak)
. If there is no ETag the return value is(None, None)
.
-
make_conditional(request_or_environ, accept_ranges=False, complete_length=None)
-
Make the response conditional to the request. This method works best if an etag was defined for the response already. The
add_etag
method can be used to do that. If called without etag just the date header is set.This does nothing if the request method in the request or environ is anything but GET or HEAD.
For optimal performance when handling range requests, it’s recommended that your response data object implements
seekable
,seek
andtell
methods as described byio.IOBase
. Objects returned bywrap_file()
automatically implement those methods.It does not remove the body of the response because that’s something the
__call__()
function does for us automatically.Returns self so that you can do
return resp.make_conditional(req)
but modifies the object in-place.Parameters: - request_or_environ – a request object or WSGI environment to be used to make the response conditional against.
-
accept_ranges – This parameter dictates the value of
Accept-Ranges
header. IfFalse
(default), the header is not set. IfTrue
, it will be set to"bytes"
. IfNone
, it will be set to"none"
. If it’s a string, it will use this value. -
complete_length – Will be used only in valid Range Requests. It will set
Content-Range
complete length value and computeContent-Length
real value. This parameter is mandatory for successful Range Requests completion.
Raises: RequestedRangeNotSatisfiable
ifRange
header could not be parsed or satisfied.
-
set_etag(etag, weak=False)
-
Set the etag, and override the old one if there was one.
-
User Agent
-
class werkzeug.wrappers.UserAgentMixin
-
Adds a
user_agent
attribute to the request object which contains the parsed user agent of the browser that triggered the request as aUserAgent
object.-
user_agent
-
The current user agent.
-
Extra Mixin Classes
These mixins are not included in the default Request
and Response
classes. They provide extra behavior that needs to be opted into by creating your own subclasses:
class Response(JSONMixin, BaseResponse): pass
JSON
-
class werkzeug.wrappers.json.JSONMixin
-
Mixin to parse
data
as JSON. Can be mixed in for bothRequest
andResponse
classes.If simplejson is installed it is preferred over Python’s built-in
json
module.-
get_json(force=False, silent=False, cache=True)
-
Parse
data
as JSON.If the mimetype does not indicate JSON (application/json, see
is_json()
), this returnsNone
.If parsing fails,
on_json_loading_failed()
is called and its return value is used as the return value.Parameters: - force – Ignore the mimetype and always try to parse JSON.
-
silent – Silence parsing errors and return
None
instead. - cache – Store the parsed JSON to return for subsequent calls.
-
is_json
-
Check if the mimetype indicates JSON data, either application/json or application/*+json.
-
json
-
The parsed JSON data if
mimetype
indicates JSON (application/json, seeis_json()
).Calls
get_json()
with default arguments.
-
json_module
-
A module or other object that has
dumps
andloads
functions that match the API of the built-injson
module.alias of
_JSONModule
-
on_json_loading_failed(e)
-
Called if
get_json()
parsing fails and isn’t silenced. If this method returns a value, it is used as the return value forget_json()
. The default implementation raisesBadRequest
.
-
© 2007–2020 Pallets
Licensed under the BSD 3-clause License.
https://werkzeug.palletsprojects.com/en/1.0.x/wrappers/