Building a Response
The request handler instance builds the response using its response property.
This is initialized to an empty WebOb
Response object by the
The response object’s acts as a file-like object that can be used for
writing the body of the response:
The response buffers all output in memory, then sends the final output when
the handler exits. webapp2 does not support streaming data to the client.
clear() method erases the contents of the output buffer, leaving it
If the data written to the output stream is a Unicode value, or if the
response includes a
Content-Type header that ends with
webapp2 encodes the output as UTF-8. By default, the
text/html; charset=utf-8, including the encoding behavior. If the
Content-Type is changed to have a different charset, webapp2 assumes the
output is a byte string to be sent verbatim.
Cookies are set in the response object. The methods to handle cookies are:
- set_cookie(key, value=’‘, max_age=None, path=’/’, domain=None, secure=None, httponly=False, comment=None, expires=None, overwrite=False)
- Sets a cookie.
- delete_cookie(key, path=’/’, domain=None)
- Deletes a cookie previously set in the client.
- Unsets a cookie previously set in the response object. Note that this
doesn’t delete the cookie from clients, only from the response.
# Saves a cookie in the client.
response.set_cookie('some_key', 'value', max_age=360, path='/',
# Deletes a cookie previously set in the client.
# Cancels a cookie previously set in the response.
key parameter is required. The parameters are:
- Cookie name.
- Cookie value.
- An expiration date. Must be a
datetime.datetime object. Use this
instead of max_age since the former is not supported by Internet Explorer.
- Cookie max age in seconds.
- URI path in which the cookie is valid.
- URI domain in which the cookie is valid.
- If True, the cookie is only available via HTTPS.
- Defines a cookie comment.
- If true, overwrites previously set (and not yet sent to the client) cookies
with the same name.
Common Response attributes
- Status code plus message, e.g., ‘404 Not Found’. The status can be set
request.status = 404, or including the message,
request.status = '404 Not Found'.
- Status code as an
int, e.g., 404.
- Status message, e.g., ‘Not Found’.
- The contents of the response, as a string.
- The contents of the response, as a unicode.
- A dictionary-like object with headers. Keys are case-insensitive. It supports
multiple values for a key, but you must use
response.headers.add(key, value) to add keys. To get all values, use
- List of headers, as a list of tuples
- Character encoding.
- ‘Content-Type’ value from the headers, e.g.,
- Dictionary of extra Content-type parameters, e.g.,
- ‘Location’ header variable, used for redirects.
- ‘ETag’ header variable. You can automatically generate an etag based on the
response body calling
Learn more about WebOb
WebOb is an open source third-party library. See the WebOb documentation
for a detailed API reference and examples.