This chapter is adapted from a portion of the WebOb documentation, originally written by Ian Bicking.
repoze.bfg uses the WebOb package to supply request and response object implementations. The request object that is passed to a repoze.bfg view is an instance of the repoze.bfg.request.Request class, which is a subclass of webob.Request. The response returned from a repoze.bfg view renderer is an instance of the webob.Response class. Users can also return an instance of webob.Response directly from a view as necessary.
WebOb is a project separate from repoze.bfg with a separate set of authors and a fully separate set of 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 repoze.bfg 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 req.environ.
Some of the most important/interesting attributes of a request object:
Also, for standard HTTP request headers there are usually attributes, for instance: req.accept_language, req.content_length, req.user_agent, as an example. These properties expose the parsed form of each header, for whatever parsing makes sense. For instance, req.if_modified_since returns a datetime object (or None if the header is was not provided).
Full API documentation for the repoze.bfg request object is available in repoze.bfg.request.
In addition to the standard WebOb attributes, repoze.bfg adds special attributes to every request: context, registry, root, subpath, traversed, view_name, virtual_root , and virtual_root_path. These attributes are documented further within the repoze.bfg.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/?id=10, where the application is mounted at http://localhost/app.
There are several methods but only a few you’ll use often:
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 Content-Type: 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 you subclass Request you can also set charset as a class-level attribute.
If it is set, then req.POST, req.GET, req.params, and req.cookies will contain unicode strings. Each has a corresponding req.str_* (like req.str_POST) that is always str and never unicode.
The response object looks a lot like the request object, though with some differences. The request object wraps a single environ object; the response object has three fundamental parts (based on WSGI):
Everything else in the object derives from this underlying state. Here’s the highlights:
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.
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 webob 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 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.
Each class is named webob.exc.HTTP*, where * is the reason for the error. For instance, webob.exc.HTTPNotFound. It subclasses Response, so you can manipulate the instances in the same way. A typical example is:
from webob.exc import HTTPNotFound from webob.exc 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 response.exception. You can use this like:
1 2 3 4 5 6 7 8 9
from webob.exc import HTTPException from webob.exc 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 attributes like content_type, charset, etc. on these exception objects.
More details about the response object API are available in the WebOb documentation . All methods and attributes of a webob.Response documented within the WebOb documentation will work against response objects created by repoze.bfg. repoze.bfg does not use a Webob Response object subclass to represent a response, it uses WebOb’s Response class directly.
Several parts of WebOb use a “multidict”; this is a dictionary where a key can have multiple values. The quintessential example is a query string like ?pref=red&pref=blue; the pref variable has two values: red and blue.
In a multidict, when you do request.GET['pref'] you’ll get back only '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 pref.
When you use operations like request.GET.items() you’ll get back something like [('pref', 'red'), ('pref', 'blue')]. All the key/value pairs will show up. Similarly request.GET.keys() returns ['pref', 'pref']. Multidict is a view on a list of tuples; all the keys are ordered, and all the values are ordered.