Request and Response Objects¶
This chapter is adapted from a portion of the WebOb documentation, originally written by Ian Bicking.
Pyramid uses the WebOb package to supply
request and response object implementations. The
request object that is passed to a Pyramid
view is an instance of the
class, which is a subclass of
response returned from a Pyramid view
renderer is an instance of the
Users can also return an instance of
from a view as necessary.
WebOb is a project separate from Pyramid with a separate set of authors and a fully separate set of documentation. Pyramid adds some functionality to the standard WebOb request, which is documented in the pyramid.request API documentation.
WebOb provides objects for HTTP requests and responses. Specifically it does this by wrapping the WSGI request environment and response status/headers/app_iter (body).
WebOb request and response objects provide many conveniences for parsing WSGI requests and forming WSGI responses. WebOb is a nice way to represent “raw” WSGI requests and responses; however, we won’t cover that use case in this document, as users of Pyramid don’t typically need to use the WSGI-related features of WebOb directly. The reference documentation shows many examples of creating requests and using response objects in this manner, however.
The request object is a wrapper around the WSGI environ dictionary. This
dictionary contains keys for each header, keys that describe the
request (including the path and query string), a file-like object for
the request body, and a variety of custom keys. You can always access
the environ with
Some of the most important/interesting attributes of a request object:
- The request method, e.g.,
- A multidict with all the variables in the query string.
- A multidict with all the variables in the request
body. This only has variables if the request was a
POSTand it is a form submission.
- A multidict with a combination of everything in
- The contents of the body of the request. This contains the entire
request body as a string. This is useful when the request is a
POSTthat is not a form submission, or a request like a
PUT. You can also get
req.body_filefor a file-like object.
- A simple dictionary of all the cookies.
- A dictionary of all the headers. This dictionary is case-insensitive.
req.urlvarsare the keyword parameters associated with the request URL.
req.urlargsare the positional parameters. These are set by products like Routes and Selector.
Also, for standard HTTP request headers there are usually attributes,
req.user_agent, as an example. These properties expose the
parsed form of each header, for whatever parsing makes sense. For
req.if_modified_since returns a datetime object
(or None if the header is was not provided).
Full API documentation for the Pyramid request object is available in pyramid.request.
Special Attributes Added to the Request by Pyramid¶
In addition to the standard WebOb attributes, Pyramid adds
special attributes to every request:
matched_route. These attributes are documented further within the
pyramid.request.Request API documentation.
In addition to these attributes, there are several ways to get the URL
of the request. I’ll show various values for an example URL
http://localhost/app/blog?id=10, where the application is mounted at
- The full request URL, with query string, e.g.,
- The host information in the URL, e.g.,
- The URL with the host, e.g.,
- The URL of the application (just the SCRIPT_NAME portion of the
path, not PATH_INFO). E.g.,
- The URL of the application including the PATH_INFO. e.g.,
- The URL including PATH_INFO without the host or scheme. e.g.,
- The URL including PATH_INFO and the query string. e.g,
- The query string in the URL, e.g.,
- Gives a URL, relative to the current URL. If
to_applicationis True, then resolves it relative to
There are several methods but only a few you’ll use often:
- Creates a new request with blank information, based at the given
URL. This can be useful for subrequests and artificial requests.
You can also use
req.copy()to copy an existing request, or for subrequests
req.copy_get()which copies the request but always turns it into a GET (which is safer to share for subrequests).
- This method calls the given WSGI application with this request, and returns a Response object. You can also use this for subrequests, or testing.
Many of the properties in the request object will return unicode
values if the request encoding/charset is provided. The client can
indicate the charset with something like
application/x-www-form-urlencoded; charset=utf8, but browsers seldom
set this. You can set the charset with
req.charset = 'utf8', or
during instantiation with
Request(environ, charset='utf8'). If
Request you can also set
charset as a class-level
If it is set, then
req.cookies will contain unicode strings. Each has a
req.str_POST) that is always
str, and never unicode.
The Pyramid response object can be imported as
pyramid.response.Response. This import location is merely a facade
for its original location:
A response object has three fundamental parts:
- The response code plus reason message, like
'200 OK'. To set the code without a message, use
response.status_int = 200.
- A list of all the headers, like
[('Content-Type', 'text/html')]. There’s a case-insensitive multidict in
response.headersthat also allows you to access these same headers.
- An iterable (such as a list or generator) that will produce the
content of the response. This is also accessible as
response.unicode_body(a unicode object, informed by
response.body_file(a file-like object; writing to it appends to
Everything else in the object derives from this underlying state. Here’s the highlights:
- The content type not including the
charsetparameter. Typical use:
response.content_type = 'text/html'.
charsetparameter of the content-type, it also informs encoding in
response.content_type_paramsis a dictionary of all the parameters.
response.set_cookie(key, value, max_age=None, path='/', ...):
- Set a cookie. The keyword arguments control the various cookie
max_ageargument is the length for the cookie to live in seconds (you may also use a timedelta object). The
Expireskey will also be set based on the value of
response.delete_cookie(key, path='/', domain=None):
- Delete a cookie from the client. This sets
max_ageto 0 and the cookie value to
- This makes this response cacheable for the given number of seconds,
secondsis 0 then the response is uncacheable (this also sets the
- The response object is a WSGI application. As an application, it
acts according to how you create it. It can do conditional
responses if you pass
conditional_response=Truewhen instantiating (or set that attribute later). It can also do HEAD and Range requests.
Like the request, most HTTP response headers are available as
properties. These are parsed, so you can do things like
response.last_modified = os.path.getmtime(filename).
The details are available in the extracted Response documentation.
Instantiating the Response¶
Of course most of the time you just want to make a response. Generally any attribute of the response can be passed in as a keyword argument to the class; e.g.:
from pyramid.response import Response response = Response(body='hello world!', content_type='text/plain')
The status defaults to
'200 OK'. The content_type does not default to
anything, though if you subclass
pyramid.response.Response and set
default_content_type you can override this behavior.
To facilitate error responses like
404 Not Found, the module
webob.exc contains classes for each kind of error response. These
include boring, but appropriate error bodies. The exceptions exposed by this
module, when used under Pyramid, should be imported from the
pyramid.httpexceptions “facade” module. This import location is merely
a facade for the original location of these exceptions:
Each class is named
* is the reason
for the error. For instance,
pyramid.Response, so you can manipulate the instances in
the same way. A typical example is:
1 2 3 4 5 6
from pyramid.httpexceptions import HTTPNotFound from pyramid.httpexceptions import HTTPMovedPermanently response = HTTPNotFound('There is no such resource') # or: response = HTTPMovedPermanently(location=new_url)
These are not exceptions unless you are using Python 2.5+, because
they are new-style classes which are not allowed as exceptions until
Python 2.5. To get an exception object use
You can use this like:
1 2 3 4 5 6 7 8 9
from pyramid.httpexceptions import HTTPException from pyramid.httpexceptions import HTTPNotFound def aview(request): try: # ... stuff ... raise HTTPNotFound('No such resource').exception except HTTPException, e: return request.get_response(e)
The exceptions are still WSGI applications, but you cannot set
charset, etc. on these exception
Several parts of WebOb use a “multidict”; this is a dictionary where a
key can have multiple values. The quintessential example is a query
pref variable has two
In a multidict, when you do
request.GET['pref'] you’ll get back
'blue' (the last value of
pref). Sometimes returning a
string, and sometimes returning a list, is the cause of frequent
exceptions. If you want all the values back, use
request.GET.getall('pref'). If you want to be sure there is one
and only one value, use
request.GET.getone('pref'), which will
raise an exception if there is zero or more than one value for
When you use operations like
request.GET.items() you’ll get back
[('pref', 'red'), ('pref', 'blue')]. All the
key/value pairs will show up. Similarly
['pref', 'pref']. Multidict is a view on a list of
tuples; all the keys are ordered, and all the values are ordered.