Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
pyramid.pdf
Скачиваний:
10
Добавлен:
24.03.2015
Размер:
3.82 Mб
Скачать

14. REQUEST AND RESPONSE OBJECTS

14.1 Request

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:

req.method: The request method, e.g., ’GET’, ’POST’

req.GET: A multidict with all the variables in the query string.

req.POST: A multidict with all the variables in the request body. This only has variables if the request was a POST and it is a form submission.

req.params: A multidict with a combination of everything in req.GET and req.POST.

req.body: 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 POST that is not a form submission, or a request like a PUT. You can also get req.body_file for a file-like object.

req.json_body The JSON-decoded contents of the body of the request. See Dealing With A JSONEncoded Request Body.

req.cookies: A simple dictionary of all the cookies.

req.headers: A dictionary of all the headers. This dictionary is case-insensitive.

req.urlvars and req.urlargs: req.urlvars are the keyword parameters associated with the request URL. req.urlargs are the positional parameters. These are set by products like Routes and Selector.

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).

latex-note.png

Full API documentation for the Pyramid request object is available in pyra-

mid.request.

164

14.1. REQUEST

14.1.1 Special Attributes Added to the Request by Pyramid

In addition to the standard WebOb attributes, Pyramid adds special attributes to every request: context, registry, root, subpath, traversed, view_name, virtual_root, virtual_root_path, session, matchdict, and matched_route. These attributes are documented further within the pyramid.request.Request API documentation.

14.1.2 URLs

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 http://localhost/app.

req.url: The full request URL, with query string, e.g., http://localhost/app/blog?id=10

req.host: The host information in the URL, e.g., localhost

req.host_url: The URL with the host, e.g., http://localhost

req.application_url: The URL of the application (just the SCRIPT_NAME portion of the path, not PATH_INFO). E.g., http://localhost/app

req.path_url: The URL of the application including the PATH_INFO. e.g., http://localhost/app/blog

req.path: The URL including PATH_INFO without the host or scheme. e.g., /app/blog

req.path_qs: The URL including PATH_INFO and the query string. e.g, /app/blog?id=10

req.query_string: The query string in the URL, e.g., id=10

req.relative_url(url, to_application=False): Gives a URL, relative to the current URL. If to_application is True, then resolves it relative to req.application_url.

14.1.3 Methods

There are methods of request objects documented in pyramid.request.Request but you’ll find that you won’t use very many of them. Here are a couple that might be useful:

Request.blank(base_url): 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).

req.get_response(wsgi_application): This method calls the given WSGI application with this request, and returns a pyramid.response.Response object. You can also use this for subrequests, or testing.

165

14. REQUEST AND RESPONSE OBJECTS

14.1.4 Unicode

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_* (e.g., req.str_POST) that is always a str, and never unicode.

14.1.5 Multidict

Several attributes of a WebOb request are “multidict”; structures (such as request.GET, request.POST, and request.params). A multidict 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.

API documentation for a multidict exists as pyramid.interfaces.IMultiDict.

14.1.6 Dealing With A JSON-Encoded Request Body

latex-note.png

this feature is new as of Pyramid 1.1.

166

14.1. REQUEST

pyramid.request.Request.json_body is a property that returns a JSON -decoded representation of the request body. If the request does not have a body, or the body is not a properly JSON-encoded value, an exception will be raised when this attribute is accessed.

This attribute is useful when you invoke a Pyramid view callable via e.g. jQuery’s $.ajax function, which has the potential to send a request with a JSON-encoded body.

Using request.json_body is equivalent to:

from json import loads

loads(request.body, encoding=request.charset)

Here’s how to construct an AJAX request in Javascript using jQuery that allows you to use the request.json_body attribute when the request is sent to a Pyramid application:

jQuery.ajax({type:’POST’,

url: ’http://localhost:6543/’, // the pyramid server data: JSON.stringify({’a’:1}),

contentType: ’application/json; charset=utf-8’});

When such a request reaches a view in your application, the request.json_body attribute will be available in the view callable body.

@view_config(renderer=’string’) def aview(request):

print request.json_body return ’OK’

For the above view, printed to the console will be:

{u’a’: 1}

For bonus points, here’s a bit of client-side code that will produce a request that has a body suitable for reading via request.json_body using Python’s urllib2 instead of a Javascript AJAX request:

import urllib2 import json

json_payload = json.dumps({’a’:1})

headers = {’Content-Type’:’application/json; charset=utf-8’}

req = urllib2.Request(’http://localhost:6543/’, json_payload, headers) resp = urllib2.urlopen(req)

167

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]