Request / Response Objects

The request and response objects wrap the WSGI environment or the returnvalue 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 responsephase. The Request class wraps the environ for easier access torequest variables (form data, request headers etc.).

The Response on the other hand is a standard WSGI application thatyou can create. The simple hello world in Werkzeug looks like this:

  1. from werkzeug.wrappers import Response
  2. application = Response('Hello World!')

To make it more useful you can replace it with a function and do someprocessing:

  1. from werkzeug.wrappers import Request, Response
  2.  
  3. def application(environ, start_response):
  4. request = Request(environ)
  5. response = Response("Hello %s!" % request.args.get('name', 'World!'))
  6. return response(environ, start_response)

Because this is a very common task the Request object providesa helper for that. The above code can be rewritten like this:

  1. from werkzeug.wrappers import Request, Response
  2.  
  3. @Request.application
  4. def application(request):
  5. return Response("Hello %s!" % request.args.get('name', 'World!'))

The application is still a valid WSGI application that accepts theenvironment and start_response callable.

Mutability and Reusability of Wrappers

The implementation of the Werkzeug request and response objects are tryingto guard you from common pitfalls by disallowing certain things as much aspossible. This serves two purposes: high performance and avoiding ofpitfalls.

For the request object the following rules apply:

  • The request object is immutable. Modifications are not supported bydefault, you may however replace the immutable attributes with mutableattributes if you need to modify it.
  • The request object may be shared in the same thread, but is not threadsafe itself. If you need to access it from multiple threads, uselocks 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() wascalled.
  • Since Werkzeug 0.6 it’s safe to use the same response object formultiple WSGI responses.
  • It’s possible to create copies using copy.deepcopy.

Base Wrappers

These objects implement a common set of operations. They are missing fancyaddon functionality like user agent parsing or etag handling. These featuresare available by mixing in various mixin classes or using Request andResponse.

  • class werkzeug.wrappers.BaseRequest(environ, populate_request=True, shallow=False)
  • Very basic request object. This does not implement advanced stuff likeentity tag parsing or cache controls. The request object is created withthe WSGI environment as first argument and will add itself to the WSGIenvironment as 'werkzeug.request' unless it’s created withpopulate_request set to False.

There are a couple of mixins available that add additional functionalityto the request object, there is also a class called Request whichsubclasses BaseRequest and all the important mixins.

It’s a good idea to create a custom subclass of the BaseRequestand add missing functionality either via mixins or direct implementation.Here an example for such subclasses:

  1. from werkzeug.wrappers import BaseRequest, ETagRequestMixin
  2.  
  3. class Request(BaseRequest, ETagRequestMixin):
  4. pass

Request objects are read only. As of 0.5 modifications are notallowed in any place. Unlike the lower level parsing functions therequest 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 moredetails about customizing the behavior.

Per default the request object will be added to the WSGIenvironment as werkzeug.request to support the debugging system.If you don’t want that, set populate_request to False.

If shallow is True the environment is initialized as shallowobject around the environ. Every operation that would modify theenviron in any way (such as consuming form data) raises an exceptionunless the shallow attribute is explicitly set to False. Thisis useful for middlewares where you don’t want to consume the formdata by accident. A shallow request is not populated to the WSGIenvironment.

Changed in version 0.5: read-only mode was enforced by using immutables classes for alldata.

  • environ
  • The WSGI environment that the request object uses for data retrival.

  • shallow

  • True if this request object is shallow (does not modify environ),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()_and _seek() methods that is both writeable and readable.

The default implementation returns a temporary file if the totalcontent length is higher than 500KB. Because many browsers do notprovide a content length for the files only the total contentlength matters.

Parameters:

  1. - **total_content_length** the total content length of all thedata in the request combined. This valueis guaranteed to be there.
  2. - **content_type** the mimetype of the uploaded file.
  3. - **filename** the filename of the uploaded file. May be _None_.
  4. - **content_length** the length of this file. This value is usuallynot provided because webbrowsers do not providethis value.
  • access_route
  • If a forwarded header exists this is a list of all ip addressesfrom the client ip to the last proxy server.

  • classmethod application(f)

  • Decorate a function as responder that accepts the request asthe last argument. This works like the responder()decorator but the function is passed the request object as thelast argument and the request object will be closedautomatically:

  1. @Request.applicationdef my_wsgi_app(request): return Response('Hello World!')

As of Werkzeug 0.14 HTTP exceptions are automatically caught andconverted to responses instead of failing.

Parameters:f – the WSGI callable to decorateReturns:a new WSGI callable

  • args
  • The parsed URL parameters (the part in the URL after the questionmark).

By default anImmutableMultiDictis returned from this function. This can be changed by settingparameter_storage_class to a different type. This mightbe necessary if the order of the form data is important.

  • base_url
  • Like url but without the querystringSee also: trusted_hosts.

  • charset = 'utf-8'

  • the charset for the request, defaults to utf-8

  • close()

  • Closes associated resources of this request object. Thiscloses all file handles explicitly. You can also use the requestobject in a with statement which will automatically close it.

New in version 0.9.

  • cookies
  • A dict with the contents of all cookies transmitted withthe request.

  • data

  • Contains the incoming request data as string in case it came witha mimetype Werkzeug does not handle.

  • dict_storage_class

  • alias of werkzeug.datastructures.ImmutableTypeConversionDict

  • disabledata_descriptor = False_

  • Indicates whether the data descriptor should be allowed to read andbuffer up the input stream. By default it’s enabled.

New in version 0.9.

  • encodingerrors = 'replace'_
  • the error handling procedure for errors, defaults to ‘replace’

  • files

  • MultiDict object containingall uploaded files. Each key in files is the name from the<input type="file" name="">. Each value in files is aWerkzeug FileStorage object.

It basically behaves like a standard file object you know from Python,with the difference that it also has asave() function that canstore the file on the filesystem.

Note that files will only contain data if the request method wasPOST, 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 formore details about the used data structure.

  • form
  • The form parameters. By default anImmutableMultiDictis returned from this function. This can be changed by settingparameter_storage_class to a different type. This mightbe necessary if the order of the form data is important.

Please keep in mind that file uploads will not end up here, but insteadin the files attribute.

Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POSTand PUT requests.

  • form_data_parser_class
  • alias of werkzeug.formparser.FormDataParser

  • classmethod fromvalues(args, *kwargs_)

  • Create a new request object based on the values provided. Ifenviron is given missing values are filled from there. This method isuseful 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 clientobject (Client) that allows to create multipart requests,support for cookies etc.

This accepts the same options as theEnvironBuilder.

Changed in version 0.5: This method now accepts the same arguments asEnvironBuilder. Because of this theenviron parameter is now called environ_overrides.

Returns:request object

  • full_path
  • Requested path as unicode, including the query string.

  • getdata(_cache=True, as_text=False, parse_form_data=False)

  • This reads the buffered incoming data from the client into onebytestring. By default this is cached but that behavior can bechanged by setting cache to False.

Usually it’s a bad idea to call this method without checking thecontent length first as a client could send dozens of megabytes or moreto cause memory problems on the server.

Note that if the form data was already parsed this method will notreturn anything as form data parsing does not cache the data likethis method does. To implicitly invoke form data parsing functionset parse_form_data to True. When this is done the return valueof this method will be an empty string if the form parser handlesthe data. This generally is not necessary as if the whole data iscached (which is the default) the form parser will used the cacheddata to parse the form data. Please be generally aware of checkingthe content length first in any case before calling this methodto avoid exhausting server memory.

If as_text is set to True the return value will be a decodedunicode string.

New in version 0.9.

  • headers
  • The headers from the WSGI environ as immutableEnvironHeaders.

  • 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 aWSGI server that spawns multiple processes.

  • is_multithread

  • boolean that is True if the application is served by amultithreaded WSGI server.

  • is_run_once

  • boolean that is True if the application will beexecuted only once in a process lifetime. This is the case forCGI for example, but it’s not guaranteed that the execution onlyhappens one time.

  • is_secure

  • True if the request is secure.

  • is_xhr

  • True if the request was triggered via a JavaScript XMLHttpRequest.This only works with libraries that support the X-Requested-Withheader and set it to “XMLHttpRequest”. Libraries that do that areprototype, jQuery and Mochikit and probably some more.

Deprecated since version 0.13: X-Requested-With is not standard and is unreliable. Youmay be able to use AcceptMixin.accept_mimetypesinstead.

New in version 0.8.

  • maxcontent_length = None_
  • the maximum content length. This is forwarded to the form dataparsing function (parse_form_data()). When set and theform or files attribute is accessed and theparsing fails because more than the specified value is transmitteda RequestEntityTooLarge exception is raised.

Have a look at Dealing with Request Data for more details.

New in version 0.5.

  • maxform_memory_size = None_
  • the maximum form field size. This is forwarded to the form dataparsing function (parse_form_data()). When set and theform or files attribute is accessed and thedata 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.

New in version 0.5.

  • method
  • The request method. (For example 'GET' or 'POST').

  • parameter_storage_class

  • alias of werkzeug.datastructures.ImmutableMultiDict

  • path

  • Requested path as unicode. This works a bit like the regular pathinfo 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 thescript is protected, this attribute contains the username theuser has authenticated as.

  • scheme

  • URL scheme (http or https).

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 mimetypethe data is stored unmodified in this stream for consumption. Mostof the time it is a better idea to use data which will giveyou that data as a string. The stream only returns the data once.

Unlike input_stream this stream is properly guarded that youcan’t accidentally read past the length of the input. Werkzeug willinternally always refer to this stream to read data which makes itpossible to wrap this object with a stream that does filtering.

Changed in version 0.9: This stream is now always available but might be consumed by theform parser later on. Previously the stream was only set if noparsing happened.

  • trustedhosts = None_
  • Optionally a list of hosts that is trusted by this request. By defaultall hosts are trusted which means that whatever the client sends thehost is will be accepted.

Because Host and X-Forwarded-Host headers can be set to any value bya malicious client, it is recommended to either set this property orimplement similar validation in the proxy (if application is being runbehind one).

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

New in version 0.6.

  • url_root
  • The full URL root (with hostname), this is the applicationroot as IRI.See also: trusted_hosts.

  • values

  • A werkzeug.datastructures.CombinedMultiDict that combinesargs and form.

  • want_form_data_parsed

  • Returns True if the request method carries content. As ofWerkzeug 0.9 this will be the case if a content type is transmitted.

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 objectis that it’s a regular WSGI application. It’s initialized with a coupleof response parameters (headers, body, status code etc.) and will start avalid WSGI response when called with the environ and start responsecallable.

Because it’s a WSGI application itself processing usually ends before theactual response is sent to the server. This helps debugging systemsbecause they can catch all the exceptions before responses are started.

Here a small example WSGI application that takes advantage of theresponse objects:

  1. from werkzeug.wrappers import BaseResponse as Response
  2.  
  3. def index():
  4. return Response('Index page')
  5.  
  6. def application(environ, start_response):
  7. path = environ.get('PATH_INFO') or '/'
  8. if path == '/':
  9. response = index()
  10. else:
  11. response = Response('Not Found', status=404)
  12. return response(environ, start_response)

Like BaseRequest which object is lacking a lot of functionalityimplemented in mixins. This gives you a better control about the actualAPI of your response objects, so you can create subclasses and add customfunctionality. 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 theforce_type() method. This is useful if you’re working with differentsubclasses of response objects and you want to post process them with aknown interface.

Per default the response object will assume all the text data is _utf-8_encoded. Please refer to the unicode chapter for moredetails about customizing the behavior.

Response can be any kind of iterable or string. If it’s a string it’sconsidered being an iterable with one item which is the string passed.Headers can be a list of tuples or aHeaders object.

Special note for mimetype and content_type: For most mime typesmimetype and content_type work the same, the difference affectsonly ‘text’ mimetypes. If the mimetype passed with mimetype is amimetype starting with text/, the charset parameter of the responseobject is appended to it. In contrast the content_type parameter isalways added as header unmodified.

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 aHeaders 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 Trueiter_encoded() is notcalled before iteration which makes itpossible to pass special iterators throughunchanged (see wrap_file() for moredetails.)
  • response
  • The application iterator. If constructed from a string this will be alist, otherwise the object provided as application iterator. (The firstargument passed to BaseResponse)

  • headers

  • A Headers object representing the response headers.

  • status_code

  • The response status as integer.

  • direct_passthrough

  • If directpassthrough=True was passed to the response object or ifthis attribute was set to _True before using the response object asWSGI application, the wrapped iterator is returned unchanged. Thismakes it possible to pass a special wsgi.file_wrapper to the responseobject. See wrap_file() for more details.

  • call(environ, start_response)

  • Process this response as WSGI application.

Parameters:

  1. - **environ** the WSGI environment.
  2. - **start_response** the response callable provided by the WSGIserver.Returns:

an application iterator

  • ensure_sequence(_mutable=False)
  • This method can be called by methods that need a sequence. Ifmutable is true, it will also ensure that the response sequenceis a standard Python list.

New in version 0.6.

  • autocorrectlocation_header = True_
  • Should this response object correct the location header to be RFCconformant? This is true by default.

New in version 0.8.

  • automaticallyset_content_length = True_
  • Should this response object automatically set the content-lengthheader if possible? This is true by default.

New in version 0.8.

  • calculate_content_length()
  • Returns the content length if available or None otherwise.

  • callon_close(_func)

  • Adds a function to the internal list of functions that shouldbe called as part of closing down the response. Since 0.7 thisfunction also returns the function that was passed so that thiscan be used as a decorator.

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 objectin a with statement which will automatically close it.

New in version 0.9: Can now be used in a with statement.

  • data
  • A descriptor that calls get_data() and set_data().

  • defaultmimetype = 'text/plain'_

  • the default mimetype if none is provided.

  • defaultstatus = 200_

  • the default status if none is provided.

  • deletecookie(_key, path='/', domain=None)

  • Delete a cookie. Fails silently if key doesn’t exist.

Parameters:

  1. - **key** the key (name) of the cookie to be deleted.
  2. - **path** if the cookie that should be deleted was limited to apath, the path has to be defined here.
  3. - **domain** if the cookie that should be deleted was limited to adomain, that domain has to be defined here.
  • classmethod forcetype(_response, environ=None)
  • Enforce that the WSGI response is a response object of the currenttype. Werkzeug will use the BaseResponse internally in manysituations like the exceptions. If you call get_response() on anexception you will get back a regular BaseResponse object, evenif you are using a custom subclass.

This method can enforce a given response type, and it will alsoconvert arbitrary WSGI callables into response objects if an environis provided:

  1. # convert a Werkzeug response object into an instance of the
  2. # MyResponseClass subclass.
  3. response = MyResponseClass.force_type(response)
  4.  
  5. # convert any WSGI application into a response object
  6. response = MyResponseClass.force_type(response, environ)

This is especially useful if you want to post-process responses inthe main dispatcher and use functionality provided by your subclass.

Keep in mind that this will modify response objects in place ifpossible!

Parameters:

  1. - **response** a response object or wsgi application.
  2. - **environ** a WSGI environment object.Returns:

a response object.

  • freeze()
  • Call this method if you want to make your response object ready forbeing pickled. This buffers the generator if there is one. It willalso set the Content-Length header to the length of the body.

Changed in version 0.6: The Content-Length header is now set.

  • classmethod fromapp(_app, environ, buffered=False)
  • Create a new response object from an application output. Thisworks best if you pass it an application that returns a generator allthe time. Sometimes applications may use the write() callablereturned by the start_response function. This tries to resolve suchedge cases automatically. But if you don’t get the expected outputyou should set buffered to True which enforces buffering.

Parameters:

  1. - **app** the WSGI application to execute.
  2. - **environ** the WSGI environment to execute against.
  3. - **buffered** set to _True_ to enforce buffering.Returns:

a response object.

  • getapp_iter(_environ)
  • Returns the application iterator for the given environ. Dependingon the request method and the current status code the return valuemight be an empty response rather than the one from the response.

If the request method is HEAD or the status code is in a rangewhere the HTTP specification requires an empty response, an emptyiterable is returned.

New in version 0.6.

Parameters:environ – the WSGI environment of the request.Returns:a response iterable.

  • getdata(_as_text=False)
  • The string representation of the request body. Whenever you callthis property the request iterable is encoded and flattened. Thiscan lead to unwanted behavior if you stream big data.

This behavior can be disabled by settingimplicit_sequence_conversion to False.

If as_text is set to True the return value will be a decodedunicode string.

New in version 0.9.

  • getwsgi_headers(_environ)
  • This is automatically called right before the response is startedand returns headers modified for the given environment. It returns acopy of the headers from the response with some modifications appliedif necessary.

For example the location header (if present) is joined with the rootURL of the environment. Also the content length is automatically setto zero here for certain status codes.

Changed in version 0.6: Previously that function was called fix_headers and modifiedthe response object in place. Also since 0.6, IRIs in locationand content-location headers are handled properly.

Also starting with 0.6, Werkzeug will attempt to set the contentlength if it is able to figure it out on its own. This is thecase if all the strings in the response iterable are alreadyencoded and the iterable is buffered.

Parameters:environ – the WSGI environment of the request.Returns:returns a new Headersobject.

  • getwsgi_response(_environ)
  • Returns the final WSGI response as tuple. The first item inthe tuple is the application iterator, the second the status andthe third the list of headers. The response returned is createdspecially for the given environment. For example if the requestmethod in the WSGI environment is 'HEAD' the response willbe empty and only the headers and status code will be present.

New in version 0.6.

Parameters:environ – the WSGI environment of the request.Returns:an (app_iter, status, headers) tuple.

  • implicitsequence_conversion = True_
  • if set to False accessing properties on the response object willnot 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 adaptyour code to the name change.

  • is_sequence
  • If the iterator is buffered, this property will be True. Aresponse object will consider an iterator to be buffered if theresponse attribute is a list or tuple.

New in version 0.6.

  • is_streamed
  • If the response is streamed (the response is not an iterable witha length information) this property is True. In this case streamedmeans 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 postfiltering 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 returnvalue of this method is used as application iterator unlessdirect_passthrough was activated.

  • make_sequence()

  • Converts the response iterator in a list. By default this happensautomatically if required. If implicit_sequence_conversion isdisabled, this method is not automatically called and some propertiesmight raise exceptions. This also encodes all the items.

New in version 0.6.

  • maxcookie_size = 4093_
  • Warn if a cookie header exceeds this size. The default, 4093, should besafely supported by most browsers. A cookie larger thanthis size will still be sent, but it may be ignored or handledincorrectly by some browsers. Set to 0 to disable this check.

New in version 0.13.

  • setcookie(_key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
  • 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 exceedsmax_cookie_size, but the header will still be set.

Parameters:

  1. - **key** the key (name) of the cookie to be set.
  2. - **value** the value of the cookie.
  3. - **max_age** should be a number of seconds, or _None_ (default) ifthe cookie should last only as long as the clientsbrowser session.
  4. - **expires** should be a _datetime_ object or UNIX timestamp.
  5. - **path** limits the cookie to a given path, per default it willspan the whole domain.
  6. - **domain** if you want to set a cross-domain cookie. For example,<code>domain=&#34;.example.com&#34;</code> will set a cookie that isreadable by the domain <code>www.example.com</code>,<code>foo.example.com</code> etc. Otherwise, a cookie will onlybe readable by the domain that set it.
  7. - **secure** If _True_, the cookie will only be available via HTTPS
  8. - **httponly** disallow JavaScript to access the cookie. This is anextension to the cookie standard and probably notsupported by all browsers.
  9. - **samesite** Limits the scope of the cookie such that it will onlybe attached to requests if those requests aresame-site”.
  • setdata(_value)
  • Sets a new string as response. The value set must either by aunicode or bytestring. If a unicode string is set it’s encodedautomatically to the charset of the response (utf-8 by default).

New in version 0.9.

  • status
  • The HTTP Status code

  • status_code

  • The HTTP Status code as number

Mixin Classes

Werkzeug also provides helper mixins for various HTTP related functionalitysuch as etags, cache control, user agents etc. When subclassing you canmix those classes in to extend the functionality of the BaseRequestor BaseResponse object. Here a small example for a request objectthat parses accept headers:

  1. from werkzeug.wrappers import AcceptMixin, BaseRequest
  2.  
  3. class Request(BaseRequest, AcceptMixin):
  4. pass

The Request and Response classes subclass the BaseRequestand BaseResponse classes and implement all the mixins Werkzeug provides:

  • class werkzeug.wrappers.AcceptMixin
  • A mixin for classes with an environ attributeto get all the HTTP accept headers asAccept objects (or subclassesthereof).

    • accept_charsets
    • List of charsets this client supports asCharsetAccept object.

    • accept_encodings

    • List of encodings this client accepts. Encodings in a HTTP termare compression encodings such as gzip. For charsets have a look ataccept_charset.

    • accept_languages

    • List of languages this client accepts asLanguageAccept object.

    • accept_mimetypes

    • List of mimetypes this client supports asMIMEAccept object.
  • class werkzeug.wrappers.AuthorizationMixin
  • Adds an authorization property that represents the parsedvalue of the Authorization header asAuthorization object.

    • authorization
    • The Authorization object in parsed form.
  • class werkzeug.wrappers.ETagRequestMixin
  • Add entity tag and cache descriptors to a request object or object witha WSGI environment available as environ. This notonly provides access to etags but also to the cache control header.

    • cache_control
    • A RequestCacheControl objectfor 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.

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.

New in version 0.7.

Return type:Range

  • class werkzeug.wrappers.ETagResponseMixin
  • Adds extra functionality to a response object for etag and cachehandling. 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, youhave to mixin this method before the response base class. The defaultresponse class does not do that.

  • accept_ranges
  • The Accept-Ranges header. Even though the name wouldindicate that multiple values are supported, it must be onestring token only.

The values 'bytes' and 'none' are common.

New in version 0.7.

  • addetag(_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 specifydirectives that MUST be obeyed by all caching mechanisms along therequest/response chain.

  • content_range

  • The Content-Range header asContentRange object. Even ifthe header is not set it wil provide such an object for easiermanipulation.

New in version 0.7.

  • freeze(no_etag=False)
  • Call this method if you want to make your response object ready forpickeling. This buffers the generator if there is one. This alsosets the etag unless no_etag is set to True.

  • get_etag()

  • Return a tuple in the form (etag, is_weak). If there is noETag the return value is (None, None).

  • makeconditional(_request_or_environ, accept_ranges=False, complete_length=None)

  • Make the response conditional to the request. This method worksbest 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 dateheader is set.

This does nothing if the request method in the request or environ isanything but GET or HEAD.

For optimal performance when handling range requests, it’s recommendedthat your response data object implements seekable, seek and _tell_methods as described by io.IOBase. Objects returned bywrap_file() automatically implement those methods.

It does not remove the body of the response because that’s somethingthe 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:

  1. - **request_or_environ** a request object or WSGI environment to beused to make the response conditionalagainst.
  2. - **accept_ranges** This parameter dictates the value of_Accept-Ranges_ header. If <code>False</code> (default),the header is not set. If <code>True</code>, it will be setto <code>&#34;bytes&#34;</code>. If <code>None</code>, it will be set to<code>&#34;none&#34;</code>. If its a string, it will use thisvalue.
  3. - **complete_length** Will be used only in valid Range Requests.It will set _Content-Range_ complete lengthvalue and compute _Content-Length_ real value.This parameter is mandatory for successfulRange Requests completion.Raises:

RequestedRangeNotSatisfiableif Range header could not be parsed or satisfied.

  • setetag(_etag, weak=False)
  • Set the etag, and override the old one if there was one.
  • class werkzeug.wrappers.ResponseStreamMixin
  • Mixin for BaseRequest subclasses. Classes that inherit fromthis mixin will automatically get a stream property that providesa write-only interface to the response iterable.

    • stream
    • The response iterable as write-only stream.
  • class werkzeug.wrappers.CommonRequestDescriptorsMixin
  • A mixin for BaseRequest subclasses. Request objects thatmix this class in will automatically get descriptors for a couple ofHTTP headers with automatic type conversion.

New in version 0.5.

  • content_encoding
  • The Content-Encoding entity-header field is used as amodifier to the media-type. When present, its value indicateswhat additional content codings have been applied to theentity-body, and thus what decoding mechanisms must be appliedin order to obtain the media-type referenced by the Content-Typeheader field.

New in version 0.9.

  • content_length
  • The Content-Length entity-header field indicates the size of theentity-body in bytes or, in the case of the HEAD method, the size ofthe entity-body that would have been sent had the request been aGET.

  • content_md5

  • The Content-MD5 entity-header field, as defined inRFC 1864, is an MD5 digest of the entity-body for the purpose ofproviding an end-to-end message integrity check (MIC) of theentity-body. (Note: a MIC is good for detecting accidentalmodification of the entity-body in transit, but is not proofagainst malicious attacks.)

New in version 0.9.

  • content_type
  • The Content-Type entity-header field indicates the mediatype of the entity-body sent to the recipient or, in the case ofthe HEAD method, the media type that would have been sent hadthe request been a GET.

  • date

  • The Date general-header field represents the date andtime at which the message was originated, having the samesemantics as orig-date in RFC 822.

  • max_forwards

  • The Max-Forwards request-header field provides amechanism with the TRACE and OPTIONS methods to limit the numberof proxies or gateways that can forward the request to the nextinbound server.

  • mimetype

  • Like content_type, but without parameters (eg, withoutcharset, type etc.) and always lowercase. For example if the contenttype is text/HTML; charset=utf-8 the mimetype would be'text/html'.

  • mimetype_params

  • The mimetype parameters as dict. For example if the contenttype is text/html; charset=utf-8 the params would be{'charset': 'utf-8'}.

  • pragma

  • The Pragma general-header field is used to includeimplementation-specific directives that might apply to any recipientalong the request/response chain. All pragma directives specifyoptional behavior from the viewpoint of the protocol; however, somesystems MAY require that behavior be consistent with the directives.

  • referrer

  • The Referer[sic] request-header field allows the clientto specify, for the server’s benefit, the address (URI) of theresource 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 thatmix this class in will automatically get descriptors for a couple ofHTTP headers with automatic type conversion.

    • age
    • The Age response-header field conveys the sender’sestimate of the amount of time since the response (or itsrevalidation) was generated at the origin server.

Age values are non-negative decimal integers, representing timein seconds.

  • allow
  • The Allow entity-header field lists the set of methodssupported by the resource identified by the Request-URI. Thepurpose of this field is strictly to inform the recipient ofvalid methods associated with the resource. An Allow headerfield MUST be present in a 405 (Method Not Allowed)response.

  • content_encoding

  • The Content-Encoding entity-header field is used as amodifier to the media-type. When present, its value indicateswhat additional content codings have been applied to theentity-body, and thus what decoding mechanisms must be appliedin order to obtain the media-type referenced by the Content-Typeheader field.

  • content_language

  • The Content-Language entity-header field describes thenatural language(s) of the intended audience for the enclosedentity. Note that this might not be equivalent to all thelanguages used within the entity-body.

  • content_length

  • The Content-Length entity-header field indicates the sizeof the entity-body, in decimal number of OCTETs, sent to therecipient or, in the case of the HEAD method, the size of theentity-body that would have been sent had the request been aGET.

  • content_location

  • The Content-Location entity-header field MAY be used tosupply the resource location for the entity enclosed in themessage when that entity is accessible from a location separatefrom the requested resource’s URI.

  • content_md5

  • The Content-MD5 entity-header field, as defined inRFC 1864, is an MD5 digest of the entity-body for the purpose ofproviding an end-to-end message integrity check (MIC) of theentity-body. (Note: a MIC is good for detecting accidentalmodification of the entity-body in transit, but is not proofagainst malicious attacks.)

  • content_type

  • The Content-Type entity-header field indicates the mediatype of the entity-body sent to the recipient or, in the case ofthe HEAD method, the media type that would have been sent hadthe request been a GET.

  • date

  • The Date general-header field represents the date andtime at which the message was originated, having the samesemantics as orig-date in RFC 822.

  • expires

  • The Expires entity-header field gives the date/time afterwhich the response is considered stale. A stale cache entry maynot normally be returned by a cache.

  • last_modified

  • The Last-Modified entity-header field indicates the dateand time at which the origin server believes the variant waslast modified.

  • location

  • The Location response-header field is used to redirectthe recipient to a location other than the Request-URI forcompletion of the request or identification of a newresource.

  • mimetype

  • The mimetype (content type without charset etc.)

  • mimetype_params

  • The mimetype parameters as dict. For example if thecontent type is text/html; charset=utf-8 the params would be{'charset': 'utf-8'}.

New in version 0.5.

  • retry_after
  • The Retry-After response-header field can be used with a503 (Service Unavailable) response to indicate how long theservice 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-headerfields that fully determines, while the response is fresh,whether a cache is permitted to use the response to reply to asubsequent request without revalidation.
  • class werkzeug.wrappers.WWWAuthenticateMixin
  • Adds a www_authenticate property to a response object.

    • www_authenticate
    • The WWW-Authenticate header in a parsed form.
  • class werkzeug.wrappers.UserAgentMixin
  • Adds a user_agent attribute to the request object whichcontains the parsed user agent of the browser that triggered therequest as a UserAgent object.

    • user_agent
    • The current user agent.

Extra Mixin Classes

These mixins are not included in the default Request andResponse classes. They provide extra behavior that needs to beopted into by creating your own subclasses:

  1. class Response(JSONMixin, BaseResponse):
  2. 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-injson module.

  • getjson(_force=False, silent=False, cache=True)
  • Parse data as JSON.

If the mimetype does not indicate JSON(application/json, see is_json()), thisreturns None.

If parsing fails, on_json_loading_failed() is called andits return value is used as the return value.

Parameters:

  1. - **force** Ignore the mimetype and always try to parse JSON.
  2. - **silent** Silence parsing errors and return <code>None</code>instead.
  3. - **cache** Store the parsed JSON to return for subsequentcalls.
  • is_json
  • Check if the mimetype indicates JSON data, eitherapplication/json or application/*+json.

  • json

  • The parsed JSON data if mimetype indicates JSON(application/json, see is_json()).

Calls get_json() with default arguments.

  • json_module
  • A module or other object that has dumps and loadsfunctions that match the API of the built-in json module.

alias of _JSONModule

  • onjson_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 valuefor get_json(). The default implementation raisesBadRequest.