14. Request / Response Objects

14.1. Overview

Kay uses the request/response objects of Werkzeug which is WSGI-compliant. When accessed by browsers Kay creates request object and pass it to the view function specified by URL mapping. Views have to take the request object as the first argument, create an response object, and return it. In this chapter, we explain about the structure of request/response objects.

14.2. Request Object

  • Kay’s Request Object is an instance of the Request class of Werkzeug.
  • Views have to take the request object as the first argument.
  • The request object is immutable. Modifications are not allowed.
  • Per default the request object will assume all the text data is utf-8 encoded.
class werkzeug.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
  • CommonRequestDescriptorsMixin for common headers
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.
lang
Language that Kay estimated from the request.
user

If authentication is enabled this is the user object specified in the AUTH_USER_MODEL of settings.py

session

If session is enabled this is the session data.

See also

Using session

referrer
Referrer.
classmethod application(f)

Decorate a function as responder that accepts the request as first argument. This works like the responder() decorator but the function is passed the request object as first argument:

@Request.application
def my_wsgi_app(request):
    return Response('Hello World!')
Parameter:f – the WSGI callable to decorate
Returns:a new WSGI callable
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_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.
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.

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

Returns:request object
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 exeuction only happens 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-With header and set it to “XMLHttpRequest”. Libraries that do that are prototype, jQuery and Mochikit and probably some more.
max_forwards
The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server.
method
The transmission method. (For example 'GET' or 'POST').
mimetype
Like content_type but without parameters (eg, without charset, type etc.). For example if the content type is text/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'}.
query_string
The URL parameters as raw bytestring.
referrer
The Referer[sic] request-header field allows the client to specify, for the server’s benefit, the address (URI) of the resource from which the Request-URI was obtained (the “referrer”, although the header field is misspelled).
remote_addr
The 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.
url_charset

The charset that is assumed for URLs. Defaults to the value of charset.

New in version 0.6.

14.3. Response Object

  • Kay’s Response Object is an instance of the Response class of Werkzeug.
class werkzeug.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
  • ResponseStreamMixin to add support for the stream property
  • CommonResponseDescriptorsMixin for various HTTP descriptors
  • WWWAuthenticateMixin for HTTP authentication support
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 to True before using the response object as WSGI application, the wrapped iterator is returned unchanged. This makes it possible to pass a special wsgi.file_wrapper to the response object. See wrap_file() for more details.
add_etag(overwrite=False, weak=False)
Add an etag for the current response if there is none yet.
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.
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.
call_on_close(func)

Adds a function to the internal list of functions that should be called as part of closing down the response.

New in version 0.6.

close()
Close the wrapped response if possible.
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_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.
data

The string representation of the request body. Whenever you access this property the request iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data.

This behavior can be disabled by setting implicit_seqence_conversion to False.

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.

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.
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.
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 call get_response() on an exception you will get back a regular BaseResponse 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.

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 the start_response function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should set buffered to True which enforces buffering.

Parameters:
  • app – 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.

New in version 0.6.

Parameter:environ – the WSGI environment of the request.
Returns:a response iterable.
get_etag()
Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None).
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.

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.

Parameter: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 first 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.

Parameter:environ – the WSGI environment of the request.
Returns:an (app_iter, status, headers) tuple.
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.

New in version 0.6.

is_streamed

If the response is streamed (the response is not a 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 usully True if a generator is passed to the response object.

This is useful for checking before applying some sort of post filtering that should not take place for streamed responses.

iter_encoded(charset=None)

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.

Changed in version 0.6.

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.
make_conditional(request_or_environ)

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.

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.

Parameter:request_or_environ – a request object or WSGI environment to be used to make the response conditional against.
make_sequence()

Converts the response iterator in a list. By default this happens automatically if required. If implicit_seqence_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.

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

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.

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.

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.
  • domain – if you want to set a cross-domain cookie. For example, domain=".example.com" will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it.
  • path – limits the cookie to a given path, per default it will span the whole domain.
set_etag(etag, weak=False)
Set the etag, and override the old one if there was one.
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.
www_authenticate
The WWW-Authenticate header in a parsed form.

14.3.1. Throwing HTTP exceptions

There are various exceptions in :mod:werkzeug.exceptions. Each exception’s name represents which type of HTTP Error. You can raise these exceptions when you want return such errors to the users.

Here are the list of exceptions:

class werkzeug.exceptions.HTTPException
class werkzeug.exceptions.BadRequest
class werkzeug.exceptions.Unauthorized
class werkzeug.exceptions.Forbidden
class werkzeug.exceptions.NotFound
class werkzeug.exceptions.MethodNotAllowed
class werkzeug.exceptions.NotAcceptable
class werkzeug.exceptions.RequestTimeout
class werkzeug.exceptions.Gone
class werkzeug.exceptions.LengthRequired
class werkzeug.exceptions.PreconditionFailed
class werkzeug.exceptions.RequestEntityTooLarge
class werkzeug.exceptions.RequestURITooLarge
class werkzeug.exceptions.UnsupportedMediaType
class werkzeug.exceptions.InternalServerError
class werkzeug.exceptions.NotImplemented
class werkzeug.exceptions.BadGateway
class werkzeug.exceptions.ServiceUnavailable

Table Of Contents

Previous topic

13. Dump and Restore

Next topic

15. Middleware

This Page