WebOb Reference

Introduction

This document covers all the details of the Request and Response objects. It is written to be testable with doctest — this affects the flavor of the documentation, perhaps to its detriment. But it also means you can feel confident that the documentation is correct.

Note

All of the code samples below are for Python 3, and will not function as-is on Python 2.

This is a somewhat different approach to reference documentation compared to the extracted documentation for the request and response.

Request

The primary object in WebOb is webob.Request, a wrapper around a WSGI environment.

The basic way you create a request object is simple enough:

  1. >>> from webob import Request
  2. >>> environ = {'wsgi.url_scheme': 'http', ...}
  3. >>> req = Request(environ)

(Note that the WSGI environment is a dictionary with a dozen required keys, so it’s a bit lengthly to show a complete example of what it would look like — usually your WSGI server will create it.)

The request object wraps the environment; it has very little internal state of its own. Instead attributes you access read and write to the environment dictionary.

You don’t have to understand the details of WSGI to use this library; this library handles those details for you. You also don’t have to use this exclusively of other libraries. If those other libraries also keep their state in the environment, multiple wrappers can coexist. Examples of libraries that can coexist include paste.wsgiwrappers.Request (used by Pylons) and yaro.Request.

The WSGI environment has a number of required variables. To make it easier to test and play around with, the Request class has a constructor that will fill in a minimal environment:

  1. >>> req = Request.blank('/article?id=1')
  2. >>> from pprint import pprint
  3. >>> pprint(req.environ)
  4. {'HTTP_HOST': 'localhost:80',
  5. 'PATH_INFO': '/article',
  6. 'QUERY_STRING': 'id=1',
  7. 'REQUEST_METHOD': 'GET',
  8. 'SCRIPT_NAME': '',
  9. 'SERVER_NAME': 'localhost',
  10. 'SERVER_PORT': '80',
  11. 'SERVER_PROTOCOL': 'HTTP/1.0',
  12. 'wsgi.errors': <...TextIOWrapper ...'<stderr>' ...>,
  13. 'wsgi.input': <...IO object at 0x...>,
  14. 'wsgi.multiprocess': False,
  15. 'wsgi.multithread': False,
  16. 'wsgi.run_once': False,
  17. 'wsgi.url_scheme': 'http',
  18. 'wsgi.version': (1, 0)}

Request Body

req.body is a file-like object that gives the body of the request (e.g., a POST form, the body of a PUT, etc). It’s kind of boring to start, but you can set it to a string and that will be turned into a file-like object. You can read the entire body with req.body.

  1. >>> hasattr(req.body_file, 'read')
  2. True
  3. >>> req.body
  4. b''
  5. >>> req.method = 'PUT'
  6. >>> req.body = b'test'
  7. >>> hasattr(req.body_file, 'read')
  8. True
  9. >>> req.body
  10. b'test'

Method & URL

All the normal parts of a request are also accessible through the request object:

  1. >>> req.method
  2. 'PUT'
  3. >>> req.scheme
  4. 'http'
  5. >>> req.script_name # The base of the URL
  6. ''
  7. >>> req.script_name = '/blog' # make it more interesting
  8. >>> req.path_info # The yet-to-be-consumed part of the URL
  9. '/article'
  10. >>> req.content_type # Content-Type of the request body
  11. ''
  12. >>> print(req.remote_user) # The authenticated user (there is none set)
  13. None
  14. >>> print(req.remote_addr) # The remote IP
  15. None
  16. >>> req.host
  17. 'localhost:80'
  18. >>> req.host_url
  19. 'http://localhost'
  20. >>> req.application_url
  21. 'http://localhost/blog'
  22. >>> req.path_url
  23. 'http://localhost/blog/article'
  24. >>> req.url
  25. 'http://localhost/blog/article?id=1'
  26. >>> req.path
  27. '/blog/article'
  28. >>> req.path_qs
  29. '/blog/article?id=1'
  30. >>> req.query_string
  31. 'id=1'

You can make new URLs:

  1. >>> req.relative_url('archive')
  2. 'http://localhost/blog/archive'

For parsing the URLs, it is often useful to deal with just the next path segment on PATH_INFO:

  1. >>> req.path_info_peek() # Doesn't change request
  2. 'article'
  3. >>> req.path_info_pop() # Does change request!
  4. 'article'
  5. >>> req.script_name
  6. '/blog/article'
  7. >>> req.path_info
  8. ''

Headers

All request headers are available through a dictionary-like object req.headers. Keys are case-insensitive.

  1. >>> req.headers['Content-Type'] = 'application/x-www-urlencoded'
  2. >>> sorted(req.headers.items())
  3. [('Content-Length', '4'), ('Content-Type', 'application/x-www-urlencoded'), ('Host', 'localhost:80')]
  4. >>> req.environ['CONTENT_TYPE']
  5. 'application/x-www-urlencoded'

Query & POST variables

Requests can have variables in one of two locations: the query string (?id=1), or in the body of the request (generally a POST form). Note that even POST requests can have a query string, so both kinds of variables can exist at the same time. Also, a variable can show up more than once, as in ?check=a&check=b.

For these variables WebOb uses a MultiDict, which is basically a dictionary wrapper on a list of key/value pairs. It looks like a single-valued dictionary, but you can access all the values of a key with .getall(key) (which always returns a list, possibly an empty list). You also get all key/value pairs when using .items() and all values with .values().

Some examples:

  1. >>> req = Request.blank('/test?check=a&check=b&name=Bob')
  2. >>> req.GET
  3. GET([('check', 'a'), ('check', 'b'), ('name', 'Bob')])
  4. >>> req.GET['check']
  5. 'b'
  6. >>> req.GET.getall('check')
  7. ['a', 'b']
  8. >>> list(req.GET.items())
  9. [('check', 'a'), ('check', 'b'), ('name', 'Bob')]

We’ll have to create a request body and change the method to get POST. Until we do that, the variables are boring:

  1. >>> req.POST
  2. <NoVars: Not a form request>
  3. >>> list(req.POST.items()) # NoVars can be read like a dict, but not written
  4. []
  5. >>> req.method = 'POST'
  6. >>> req.body = b'name=Joe&email=joe@example.com'
  7. >>> req.POST
  8. MultiDict([('name', 'Joe'), ('email', 'joe@example.com')])
  9. >>> req.POST['name']
  10. 'Joe'

Often you won’t care where the variables come from. (Even if you care about the method, the location of the variables might not be important.) There is a dictionary called req.params that contains variables from both sources:

  1. >>> req.params
  2. NestedMultiDict([('check', 'a'), ('check', 'b'), ('name', 'Bob'), ('name', 'Joe'), ('email', 'joe@example.com')])
  3. >>> req.params['name']
  4. 'Bob'
  5. >>> req.params.getall('name')
  6. ['Bob', 'Joe']
  7. >>> for name, value in req.params.items():
  8. ... print('%s: %r' % (name, value))
  9. check: 'a'
  10. check: 'b'
  11. name: 'Bob'
  12. name: 'Joe'
  13. email: 'joe@example.com'

The POST and GET nomenclature is historical — req.GET can be used for non-GET requests to access query parameters, and req.POST can also be used for PUT requests with the appropriate Content-Type.

  1. >>> req = Request.blank('/test?check=a&check=b&name=Bob')
  2. >>> req.method = 'PUT'
  3. >>> req.body = b'var1=value1&var2=value2&rep=1&rep=2'
  4. >>> req.environ['CONTENT_LENGTH'] = str(len(req.body))
  5. >>> req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
  6. >>> req.GET
  7. GET([('check', 'a'), ('check', 'b'), ('name', 'Bob')])
  8. >>> req.POST
  9. MultiDict([('var1', 'value1'), ('var2', 'value2'), ('rep', '1'), ('rep', '2')])

Unicode Variables

Submissions are by default UTF-8, you can force a different character set by setting the charset on the Request object explicitly. A client can indicate the character set with Content-Type: application/x-www-form-urlencoded; charset=utf8, but very few clients actually do this (sometimes XMLHttpRequest requests will do this, as JSON is always UTF8 even when a page is served with a different character set). You can force a charset, which will affect all the variables:

  1. >>> req.charset = 'utf8'
  2. >>> req.GET
  3. GET([('check', 'a'), ('check', 'b'), ('name', 'Bob')])

Cookies

Cookies are presented in a simple dictionary. Like other variables, they will be decoded into Unicode strings if you set the charset.

  1. >>> req.headers['Cookie'] = 'test=value'
  2. >>> req.cookies
  3. <RequestCookies (dict-like) with values {'test': 'value'}>

Modifying the request

The headers are all modifiable, as are other environmental variables (like req.remote_user, which maps to request.environ['REMOTE_USER']).

If you want to copy the request you can use req.copy(); this copies the environ dictionary, and the request body from environ['wsgi.input'].

The method req.remove_conditional_headers(remove_encoding=True) can be used to remove headers that might result in a 304 Not Modified response. If you are writing some intermediary it can be useful to avoid these headers. Also if remove_encoding is true (the default) then any Accept-Encoding header will be removed, which can result in gzipped responses.

Header Getters

In addition to req.headers, there are attributes for most of the request headers defined by the HTTP 1.1 specification. These attributes often return parsed forms of the headers.

Accept-* headers

There are several request headers that tell the server what the client accepts. These are accept (the Content-Type that is accepted), accept_charset (the charset accepted), accept_encoding (the Content-Encoding, like gzip, that is accepted), and accept_language (generally the preferred language of the client).

The objects returned support containment to test for acceptability. E.g.:

  1. >>> 'text/html' in req.accept
  2. True

Because no header means anything is potentially acceptable, this is returning True. We can set it to see more interesting behavior (the example means that text/html is okay, but application/xhtml+xml is preferred):

  1. >>> req.accept = 'text/html;q=0.5, application/xhtml+xml;q=1'
  2. >>> req.accept
  3. <AcceptValidHeader ('text/html;q=0.5, application/xhtml+xml')>
  4. >>> 'text/html' in req.accept
  5. True

There are a few methods for different strategies of finding a match.

  1. >>> req.accept.best_match(['text/html', 'application/xhtml+xml'])
  2. 'application/xhtml+xml'

If we just want to know everything the client prefers, in the order it is preferred:

  1. >>> list(req.accept)
  2. ['application/xhtml+xml', 'text/html']

For languages you’ll often have a “fallback” language. E.g., if there’s nothing better then use en-US (and if en-US is okay, ignore any less preferrable languages):

  1. >>> req.accept_language = 'es, pt-BR'
  2. >>> req.accept_language.best_match(['en-GB', 'en-US'], default_match='en-US')
  3. 'en-US'
  4. >>> req.accept_language.best_match(['es', 'en-US'], default_match='en-US')
  5. 'es'

Your fallback language must appear both in the offers and as the default_match to insure that it is returned as a best match if the client specified a preference for it.

  1. >>> req.accept_language = 'en-US;q=0.5, en-GB;q=0.2'
  2. >>> req.accept_language.best_match(['en-GB'], default_match='en-US')
  3. 'en-GB'
  4. >>> req.accept_language.best_match(['en-GB', 'en-US'], default_match='en-US')
  5. 'en-US'

Conditional Requests

There a number of ways to make a conditional request. A conditional request is made when the client has a document, but it is not sure if the document is up to date. If it is not, it wants a new version. If the document is up to date then it doesn’t want to waste the bandwidth, and expects a 304 Not Modified response.

ETags are generally the best technique for these kinds of requests; this is an opaque string that indicates the identity of the object. For instance, it’s common to use the mtime (last modified) of the file, plus the number of bytes, and maybe a hash of the filename (if there’s a possibility that the same URL could point to two different server-side filenames based on other variables). To test if a 304 response is appropriate, you can use:

  1. >>> server_token = 'opaque-token'
  2. >>> server_token in req.if_none_match # You shouldn't return 304
  3. False
  4. >>> req.if_none_match = server_token
  5. >>> req.if_none_match
  6. <ETag opaque-token>
  7. >>> server_token in req.if_none_match # You *should* return 304
  8. True

For date-based comparisons If-Modified-Since is used:

  1. >>> from webob import UTC
  2. >>> from datetime import datetime
  3. >>> req.if_modified_since = datetime(2006, 1, 1, 12, 0, tzinfo=UTC)
  4. >>> req.headers['If-Modified-Since']
  5. 'Sun, 01 Jan 2006 12:00:00 GMT'
  6. >>> server_modified = datetime(2005, 1, 1, 12, 0, tzinfo=UTC)
  7. >>> req.if_modified_since and req.if_modified_since >= server_modified
  8. True

For range requests there are two important headers, If-Range (which is form of conditional request) and Range (which requests a range). If the If-Range header fails to match then the full response (not a range) should be returned:

  1. >>> req.if_range
  2. IfRange(<ETag *>)
  3. >>> req.if_range = 'opaque-etag'
  4. >>> from webob import Response
  5. >>> res = Response(etag='opaque-etag')
  6. >>> res in req.if_range
  7. True

To get the range information:

  1. >>> req.range = 'bytes=0-100'
  2. >>> req.range
  3. <Range bytes 0-101>
  4. >>> cr = req.range.content_range(length=1000)
  5. >>> cr.start, cr.stop, cr.length
  6. (0, 101, 1000)

Note that the range headers use inclusive ranges (the last byte indexed is included), where Python always uses a range where the last index is excluded from the range. The .stop index is in the Python form.

Another kind of conditional request is a request (typically PUT) that includes If-Match or If-Unmodified-Since. In this case you are saying “here is an update to a resource, but don’t apply it if someone else has done something since I last got the resource”. If-Match means “do this if the current ETag matches the ETag I’m giving”. If-Unmodified-Since means “do this if the resource has remained unchanged”.

  1. >>> server_token in req.if_match # No If-Match means everything is ok
  2. True
  3. >>> req.if_match = server_token
  4. >>> server_token in req.if_match # Still OK
  5. True
  6. >>> req.if_match = 'other-token'
  7. >>> # Not OK, should return 412 Precondition Failed:
  8. >>> server_token in req.if_match
  9. False

For more on this kind of conditional request, see Detecting the Lost Update Problem Using Unreserved Checkout.

Calling WSGI Applications

The request object can be used to make handy subrequests or test requests against WSGI applications. If you want to make subrequests, you should copy the request (with req.copy()) before sending it to multiple applications, since applications might modify the request when they are run.

There’s two forms of the subrequest. The more primitive form is this:

  1. >>> req = Request.blank('/')
  2. >>> def wsgi_app(environ, start_response):
  3. ... start_response('200 OK', [('Content-type', 'text/plain')])
  4. ... return ['Hi!']
  5. >>> req.call_application(wsgi_app)
  6. ('200 OK', [('Content-type', 'text/plain')], ['Hi!'])

Note it returns (status_string, header_list, app_iter). If app_iter.close() exists, it is your responsibility to call it.

A handier response can be had with:

  1. >>> res = req.get_response(wsgi_app)
  2. >>> res
  3. <Response ... 200 OK>
  4. >>> res.status
  5. '200 OK'
  6. >>> res.headers
  7. ResponseHeaders([('Content-type', 'text/plain')])
  8. >>> res.body
  9. 'Hi!'

You can learn more about this response object in the Response section.

Ad-Hoc Attributes

You can assign attributes to your request objects. They will all go in environ['webob.adhoc_attrs'] (a dictionary).

  1. >>> req = Request.blank('/')
  2. >>> req.some_attr = 'blah blah blah'
  3. >>> new_req = Request(req.environ)
  4. >>> new_req.some_attr
  5. 'blah blah blah'
  6. >>> req.environ['webob.adhoc_attrs']
  7. {'some_attr': 'blah blah blah'}

Response

The webob.Response object contains everything necessary to make a WSGI response. Instances of it are in fact WSGI applications, but it can also represent the result of calling a WSGI application (as noted in Calling WSGI Applications). It can also be a way of accumulating a response in your WSGI application.

A WSGI response is made up of a status (like 200 OK), a list of headers, and a body (or iterator that will produce a body).

Core Attributes

The core attributes are unsurprising:

  1. >>> from webob import Response
  2. >>> res = Response()
  3. >>> res.status
  4. '200 OK'
  5. >>> res.headerlist
  6. [('Content-Type', 'text/html; charset=UTF-8'), ('Content-Length', '0')]
  7. >>> res.body
  8. b''

You can set any of these attributes, e.g.:

  1. >>> res.status = 404
  2. >>> res.status
  3. '404 Not Found'
  4. >>> res.status_code
  5. 404
  6. >>> res.headerlist = [('Content-Type', 'text/html')]
  7. >>> res.body = b'test'
  8. >>> print(res)
  9. 404 Not Found
  10. Content-Type: text/html
  11. Content-Length: 4
  12. test
  13. >>> res.body = "test"
  14. Traceback (most recent call last):
  15. ...
  16. TypeError: You cannot set Response.body to a text object (use Response.text)
  17. >>> res.text = "test"
  18. >>> res.body
  19. b'test'

You can set any attribute with the constructor, like Response(charset='UTF-8')

Headers

In addition to res.headerlist, there is dictionary-like view on the list in res.headers:

  1. >>> res.headers
  2. ResponseHeaders([('Content-Type', 'text/html'), ('Content-Length', '4')])

This is case-insensitive. It can support multiple values for a key, though only if you use res.headers.add(key, value) or read them with res.headers.getall(key).

Body & app_iter

The res.body attribute represents the entire body of the request as a single string (not unicode, though you can set it to unicode if you have a charset defined). There is also a res.app_iter attribute that reprsents the body as an iterator. WSGI applications return these app_iter iterators instead of strings, and sometimes it can be problematic to load the entire iterator at once (for instance, if it returns the contents of a very large file). Generally it is not a problem, and often the iterator is something simple like a one-item list containing a string with the entire body.

If you set the body then Content-Length will also be set, and an res.app_iter will be created for you. If you set res.app_iter then Content-Length will be cleared, but it won’t be set for you.

There is also a file-like object you can access, which will update the app_iter in-place (turning the app_iter into a list if necessary):

  1. >>> res = Response(content_type='text/plain', charset=None)
  2. >>> f = res.body_file
  3. >>> f.write('hey')
  4. Traceback (most recent call last):
  5. ...
  6. TypeError: You can only write text to Response if charset has been set
  7. >>> f.encoding
  8. >>> res.charset = 'UTF-8'
  9. >>> f.encoding
  10. 'UTF-8'
  11. >>> f.write('test')
  12. >>> res.app_iter
  13. [b'', b'test']
  14. >>> res.body
  15. b'test'

Header Getters

Like Request, HTTP response headers are also available as individual properties. These represent parsed forms of the headers.

Content-Type is a special case, as the type and the charset are handled through two separate properties:

  1. >>> res = Response()
  2. >>> res.content_type = 'text/html'
  3. >>> res.charset = 'utf8'
  4. >>> res.content_type
  5. 'text/html'
  6. >>> res.headers['content-type']
  7. 'text/html; charset=utf8'
  8. >>> res.content_type = 'application/atom+xml'
  9. >>> res.content_type_params
  10. {'charset': 'UTF-8'}
  11. >>> res.content_type_params = {'type': 'entry', 'charset': 'UTF-8'}
  12. >>> res.headers['content-type']
  13. 'application/atom+xml; charset=UTF-8; type=entry'

Other headers:

  1. >>> # Used with a redirect:
  2. >>> res.location = 'http://localhost/foo'
  3. >>> # Indicates that the server accepts Range requests:
  4. >>> res.accept_ranges = 'bytes'
  5. >>> # Used by caching proxies to tell the client how old the
  6. >>> # response is:
  7. >>> res.age = 120
  8. >>> # Show what methods the client can do; typically used in
  9. >>> # a 405 Method Not Allowed response:
  10. >>> res.allow = ['GET', 'PUT']
  11. >>> # Set the cache-control header:
  12. >>> res.cache_control.max_age = 360
  13. >>> res.cache_control.no_transform = True
  14. >>> # Tell the browser to treat the response as an attachment:
  15. >>> res.content_disposition = 'attachment; filename=foo.xml'
  16. >>> # Used if you had gzipped the body:
  17. >>> res.content_encoding = 'gzip'
  18. >>> # What language(s) are in the content:
  19. >>> res.content_language = ['en']
  20. >>> # Seldom used header that tells the client where the content
  21. >>> # is from:
  22. >>> res.content_location = 'http://localhost/foo'
  23. >>> # Seldom used header that gives a hash of the body:
  24. >>> res.content_md5 = 'big-hash'
  25. >>> # Means we are serving bytes 0-500 inclusive, out of 1000 bytes total:
  26. >>> # you can also use the range setter shown earlier
  27. >>> res.content_range = (0, 501, 1000)
  28. >>> # The length of the content; set automatically if you set
  29. >>> # res.body:
  30. >>> res.content_length = 4
  31. >>> # Used to indicate the current date as the server understands
  32. >>> # it:
  33. >>> res.date = datetime.now()
  34. >>> # The etag:
  35. >>> res.etag = 'opaque-token'
  36. >>> # You can generate it from the body too:
  37. >>> res.md5_etag()
  38. >>> res.etag
  39. '1B2M2Y8AsgTpgAmY7PhCfg'
  40. >>> # When this page should expire from a cache (Cache-Control
  41. >>> # often works better):
  42. >>> import time
  43. >>> res.expires = time.time() + 60*60 # 1 hour
  44. >>> # When this was last modified, of course:
  45. >>> res.last_modified = datetime(2007, 1, 1, 12, 0, tzinfo=UTC)
  46. >>> # Used with 503 Service Unavailable to hint the client when to
  47. >>> # try again:
  48. >>> res.retry_after = 160
  49. >>> # Indicate the server software:
  50. >>> res.server = 'WebOb/1.0'
  51. >>> # Give a list of headers that the cache should vary on:
  52. >>> res.vary = ['Cookie']

Note in each case you can general set the header to a string to avoid any parsing, and set it to None to remove the header (or do something like del res.vary).

In the case of date-related headers you can set the value to a datetime instance (ideally with a UTC timezone), a time tuple, an integer timestamp, or a properly-formatted string.

After setting all these headers, here’s the result:

  1. >>> for name, value in res.headerlist:
  2. ... print('%s: %s' % (name, value))
  3. Content-Type: application/atom+xml; charset=UTF-8; type=entry
  4. Location: http://localhost/foo
  5. Accept-Ranges: bytes
  6. Age: 120
  7. Allow: GET, PUT
  8. Cache-Control: max-age=360, no-transform
  9. Content-Disposition: attachment; filename=foo.xml
  10. Content-Encoding: gzip
  11. Content-Language: en
  12. Content-Location: http://localhost/foo
  13. Content-MD5: big-hash
  14. Content-Range: bytes 0-500/1000
  15. Content-Length: 4
  16. Date: ... GMT
  17. ETag: ...
  18. Expires: ... GMT
  19. Last-Modified: Mon, 01 Jan 2007 12:00:00 GMT
  20. Retry-After: 160
  21. Server: WebOb/1.0
  22. Vary: Cookie

You can also set Cache-Control related attributes with req.cache_expires(seconds, **attrs), like:

  1. >>> res = Response()
  2. >>> res.cache_expires(10)
  3. >>> res.headers['Cache-Control']
  4. 'max-age=10'
  5. >>> res.cache_expires(0)
  6. >>> res.headers['Cache-Control']
  7. 'max-age=0, must-revalidate, no-cache, no-store'
  8. >>> res.headers['Expires']
  9. '... GMT'

You can also use the timedelta constants defined, e.g.:

  1. >>> from webob import *
  2. >>> res = Response()
  3. >>> res.cache_expires(2*day+4*hour)
  4. >>> res.headers['Cache-Control']
  5. 'max-age=187200'

Cookies

Cookies (and the Set-Cookie header) are handled with a couple methods. Most importantly:

  1. >>> res.set_cookie('key', 'value', max_age=360, path='/',
  2. ... domain='example.org', secure=True)
  3. >>> res.headers['Set-Cookie']
  4. 'key=value; Domain=example.org; Max-Age=360; Path=/; expires=... GMT; secure'
  5. >>> # To delete a cookie previously set in the client:
  6. >>> res.delete_cookie('bad_cookie')
  7. >>> res.headers['Set-Cookie']
  8. 'bad_cookie=; Max-Age=0; Path=/; expires=... GMT'

The only other real method of note (note that this does not delete the cookie from clients, only from the response object):

  1. >>> res.unset_cookie('key')
  2. >>> res.unset_cookie('bad_cookie')
  3. >>> print(res.headers.get('Set-Cookie'))
  4. None

Binding a Request

You can bind a request (or request WSGI environ) to the response object. This is available through res.request or res.environ. This is currently only used in setting res.location, to make the location absolute if necessary.

Response as a WSGI application

A response is a WSGI application, in that you can do:

  1. >>> req = Request.blank('/')
  2. >>> status, headers, app_iter = req.call_application(res)

A possible pattern for your application might be:

  1. >>> def my_app(environ, start_response):
  2. ... req = Request(environ)
  3. ... res = Response()
  4. ... res.charset = 'UTF-8'
  5. ... res.content_type = 'text/plain'
  6. ... parts = []
  7. ... for name, value in sorted(req.environ.items()):
  8. ... parts.append('%s: %r' % (name, value))
  9. ... res.text = '\n'.join(parts)
  10. ... return res(environ, start_response)
  11. >>> req = Request.blank('/')
  12. >>> res = req.get_response(my_app)
  13. >>> print(res)
  14. 200 OK
  15. Content-Type: text/plain; charset=UTF-8
  16. Content-Length: ...
  17. HTTP_HOST: 'localhost:80'
  18. PATH_INFO: '/'
  19. QUERY_STRING: ''
  20. REQUEST_METHOD: 'GET'
  21. SCRIPT_NAME: ''
  22. SERVER_NAME: 'localhost'
  23. SERVER_PORT: '80'
  24. SERVER_PROTOCOL: 'HTTP/1.0'
  25. wsgi.errors: <...>
  26. wsgi.input: <...IO... object at ...>
  27. wsgi.multiprocess: False
  28. wsgi.multithread: False
  29. wsgi.run_once: False
  30. wsgi.url_scheme: 'http'
  31. wsgi.version: (1, 0)

Exceptions

In addition to Request and Response objects, there are a set of Python exceptions for different HTTP responses (3xx, 4xx, 5xx codes).

These provide a simple way to provide these non-200 response. A very simple body is provided.

  1. >>> from webob.exc import *
  2. >>> exc = HTTPTemporaryRedirect(location='foo')
  3. >>> req = Request.blank('/path/to/something')
  4. >>> print(str(req.get_response(exc)).strip())
  5. 307 Temporary Redirect
  6. Location: http://localhost/path/to/foo
  7. Content-Length: 126
  8. Content-Type: text/plain; charset=UTF-8
  9. \r
  10. 307 Temporary Redirect
  11. The resource has been moved to http://localhost/path/to/foo; you should be redirected automatically.

Note that only if there’s an Accept: text/html header in the request will an HTML response be given:

  1. >>> req.accept += 'text/html'
  2. >>> print(str(req.get_response(exc)).strip())
  3. 307 Temporary Redirect
  4. Location: http://localhost/path/to/foo
  5. Content-Length: 270
  6. Content-Type: text/html; charset=UTF-8
  7. <html>
  8. <head>
  9. <title>307 Temporary Redirect</title>
  10. </head>
  11. <body>
  12. <h1>307 Temporary Redirect</h1>
  13. The resource has been moved to <a href="http://localhost/path/to/foo">http://localhost/path/to/foo</a>;
  14. you should be redirected automatically.
  15. </body>
  16. </html>

Conditional WSGI Application

The Response object can handle your conditional responses for you, checking If-None-Match, If-Modified-Since, and Range/If-Range.

To enable this you must create the response like Response(conditional_response=True), or make a subclass like:

  1. >>> class AppResponse(Response):
  2. ... default_content_type = 'text/html'
  3. ... default_conditional_response = True
  4. >>> res = AppResponse(body='0123456789',
  5. ... last_modified=datetime(2005, 1, 1, 12, 0, tzinfo=UTC))
  6. >>> req = Request.blank('/')
  7. >>> req.if_modified_since = datetime(2006, 1, 1, 12, 0, tzinfo=UTC)
  8. >>> req.get_response(res)
  9. <Response ... 304 Not Modified>
  10. >>> del req.if_modified_since
  11. >>> res.etag = 'opaque-tag'
  12. >>> req.if_none_match = 'opaque-tag'
  13. >>> req.get_response(res)
  14. <Response ... 304 Not Modified>
  15. >>> req.if_none_match = '*'
  16. >>> 'x' in req.if_none_match
  17. True
  18. >>> req.if_none_match = req.if_none_match
  19. >>> 'x' in req.if_none_match
  20. True
  21. >>> req.if_none_match = None
  22. >>> 'x' in req.if_none_match
  23. False
  24. >>> req.if_match = None
  25. >>> 'x' in req.if_match
  26. True
  27. >>> req.if_match = req.if_match
  28. >>> 'x' in req.if_match
  29. True
  30. >>> req.headers.get('If-Match')
  31. '*'
  32. >>> del req.if_none_match
  33. >>> req.range = (1, 5)
  34. >>> result = req.get_response(res)
  35. >>> result.headers['content-range']
  36. 'bytes 1-4/10'
  37. >>> result.body
  38. b'1234'