Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 337 lines (259 sloc) 12.173 kB
142b823 @ianb Request docs
ianb authored
1 WebOb
2 +++++
3
54bd1f7 @ianb sphinx-ify
ianb authored
4 .. toctree::
5
6 reference
7 modules/webob
7ab0e13 @ianb Added autogenerated webob.dec docs. Fix a bunch of Sphinx warnings/e…
ianb authored
8 modules/dec
506587f @multani Add webob.static in the documentation tree and update NEWS file
multani authored
9 modules/static
54bd1f7 @ianb sphinx-ify
ianb authored
10 differences
11 file-example
12 wiki-example
13 comment-example
14 jsonrpc-example
15 do-it-yourself
16 news
17 license
9279284 @ianb Added a do-it-yourself framework doc for webob
ianb authored
18
142b823 @ianb Request docs
ianb authored
19 .. contents::
20
21 .. comment:
22
d57f294 @maluke This commit aggregates most of the work done at the 2011 PyCon Pyrami…
maluke authored
23 >>> from doctest import ELLIPSIS
35acb1d @ianb Note Sergey in the docs/etc
ianb authored
24
142b823 @ianb Request docs
ianb authored
25
26 Status & License
27 ================
28
29 WebOb is an extraction and refinement of pieces from `Paste
30 <http://pythonpaste.org/>`_. It is under active development.
31 Discussion should happen on the `Paste mailing lists
f7ba3fc @maluke switch from trac to bitbucket's issue tracker
maluke authored
32 <http://pythonpaste.org/community/>`_, and bugs can go on the `issue tracker
1143fac @maluke change links from bitbucket to github
maluke authored
33 <https://github.com/Pylons/webob/issues>`_. It was originally
a16edae @maluke fix markup
maluke authored
34 written by `Ian Bicking <http://ianbicking.org/>`_, and the primary
35 maintainer is now `Sergey Schetinin <http://self.maluke.com/>`_.
142b823 @ianb Request docs
ianb authored
36
37 WebOb is released under an `MIT-style license <license.html>`_.
38
1143fac @maluke change links from bitbucket to github
maluke authored
39 WebOb development happens on `GitHub <https://github.com/Pylons/webob>`_.
40 Development version is installable via `easy_install
41 webob==dev <https://github.com/Pylons/webob/zipball/master>`__. You
42 can clone the source code with::
d30b982 @ianb include svn link
ianb authored
43
1143fac @maluke change links from bitbucket to github
maluke authored
44 $ git clone https://github.com/Pylons/webob.git
d30b982 @ianb include svn link
ianb authored
45
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
46 Introduction
47 ============
845744b @ianb changed to .. code-block::
ianb authored
48
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
49 WebOb provides objects for HTTP requests and responses. Specifically
50 it does this by wrapping the `WSGI <http://wsgi.org>`_ request
51 environment and response status/headers/app_iter(body).
142b823 @ianb Request docs
ianb authored
52
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
53 The request and response objects provide many conveniences for parsing
54 HTTP request and forming HTTP responses. Both objects are read/write:
55 as a result, WebOb is also a nice way to create HTTP requests and
56 parse HTTP responses; however, we won't cover that use case in this
57 document. The `reference documentation <reference.html>`_ shows many
58 examples of creating requests.
142b823 @ianb Request docs
ianb authored
59
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
60 Request
61 =======
142b823 @ianb Request docs
ianb authored
62
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
63 The request object is a wrapper around the `WSGI environ dictionary
64 <http://www.python.org/dev/peps/pep-0333/#environ-variables>`_. This
65 dictionary contains keys for each header, keys that describe the
66 request (including the path and query string), a file-like object for
67 the request body, and a variety of custom keys. You can always access
68 the environ with ``req.environ``.
142b823 @ianb Request docs
ianb authored
69
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
70 Some of the most important/interesting attributes of a request
71 object:
142b823 @ianb Request docs
ianb authored
72
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
73 ``req.method``:
74 The request method, e.g., ``'GET'``, ``'POST'``
142b823 @ianb Request docs
ianb authored
75
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
76 ``req.GET``:
77 A `dictionary-like object`_ with all the variables in the query
78 string.
142b823 @ianb Request docs
ianb authored
79
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
80 ``req.POST``:
81 A `dictionary-like object`_ with all the variables in the request
82 body. This only has variables if the request was a ``POST`` and
35acb1d @ianb Note Sergey in the docs/etc
ianb authored
83 it is a form submission.
142b823 @ianb Request docs
ianb authored
84
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
85 ``req.params``:
86 A `dictionary-like object`_ with a combination of everything in
87 ``req.GET`` and ``req.POST``.
142b823 @ianb Request docs
ianb authored
88
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
89 ``req.body``:
90 The contents of the body of the request. This contains the entire
91 request body as a string. This is useful when the request is a
92 ``POST`` that is *not* a form submission, or a request like a
93 ``PUT``. You can also get ``req.body_file`` for a file-like
94 object.
845744b @ianb changed to .. code-block::
ianb authored
95
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
96 ``req.cookies``:
97 A simple dictionary of all the cookies.
142b823 @ianb Request docs
ianb authored
98
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
99 ``req.headers``:
100 A dictionary of all the headers. This is dictionary is case-insensitive.
142b823 @ianb Request docs
ianb authored
101
b3c11c1 @ianb add note about urlvars
ianb authored
102 ``req.urlvars`` and ``req.urlargs``:
103 ``req.urlvars`` is the keyword parameters associated with the
104 request URL. ``req.urlargs`` are the positional parameters.
105 These are set by products like `Routes
106 <http://routes.groovie.org/>`_ and `Selector
107 <http://lukearno.com/projects/selector/>`_.
108
9fb21d1 @ianb fix up some links, text
ianb authored
109 .. _`dictionary-like object`: #multidict
845744b @ianb changed to .. code-block::
ianb authored
110
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
111 Also, for standard HTTP request headers there are usually attributes,
112 for instance: ``req.accept_language``, ``req.content_length``,
113 ``req.user_agent``, as an example. These properties expose the
114 *parsed* form of each header, for whatever parsing makes sense. For
115 instance, ``req.if_modified_since`` returns a `datetime
116 <http://python.org/doc/current/lib/datetime-datetime.html>`_ object
117 (or None if the header is was not provided). Details are in the
118 `Request reference <class-webob.Request.html>`_.
142b823 @ianb Request docs
ianb authored
119
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
120 URLs
121 ----
845744b @ianb changed to .. code-block::
ianb authored
122
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
123 In addition to these attributes, there are several ways to get the URL
124 of the request. I'll show various values for an example URL
125 ``http://localhost/app-root/doc?article_id=10``, where the application
126 is mounted at ``http://localhost/app-root``.
142b823 @ianb Request docs
ianb authored
127
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
128 ``req.url``:
129 The full request URL, with query string, e.g.,
130 ``'http://localhost/app-root/doc?article_id=10'``
845744b @ianb changed to .. code-block::
ianb authored
131
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
132 ``req.application_url``:
c2059e9 @ianb clarify application_url; build reference.txt
ianb authored
133 The URL of the application (just the SCRIPT_NAME portion of the
134 path, not PATH_INFO). E.g., ``'http://localhost/app-root'``
142b823 @ianb Request docs
ianb authored
135
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
136 ``req.host_url``:
137 The URL with the host, e.g., ``'http://localhost'``
142b823 @ianb Request docs
ianb authored
138
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
139 ``req.relative_url(url, to_application=False)``:
140 Gives a URL, relative to the current URL. If ``to_application``
141 is True, then resolves it relative to ``req.application_url``.
142b823 @ianb Request docs
ianb authored
142
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
143 Methods
142b823 @ianb Request docs
ianb authored
144 -------
145
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
146 There are `several methods <class-webob.Request.html#__init__>`_ but
147 only a few you'll use often:
142b823 @ianb Request docs
ianb authored
148
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
149 ``Request.blank(base_url)``:
150 Creates a new request with blank information, based at the given
151 URL. This can be useful for subrequests and artificial requests.
152 You can also use ``req.copy()`` to copy an existing request, or
153 for subrequests ``req.copy_get()`` which copies the request but
16ca566 @ianb typo
ianb authored
154 always turns it into a GET (which is safer to share for
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
155 subrequests).
142b823 @ianb Request docs
ianb authored
156
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
157 ``req.get_response(wsgi_application)``:
158 This method calls the given WSGI application with this request,
159 and returns a `Response`_ object. You can also use this for
160 subrequests or testing.
142b823 @ianb Request docs
ianb authored
161
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
162 Unicode
163 -------
6ff6557 @ianb Allow arbitrary attributes to be set on the Request object, and store…
ianb authored
164
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
165 Many of the properties in the request object will return unicode
166 values if the request encoding/charset is provided. The client *can*
167 indicate the charset with something like ``Content-Type:
168 application/x-www-form-urlencoded; charset=utf8``, but browsers seldom
169 set this. You can set the charset with ``req.charset = 'utf8'``, or
170 during instantiation with ``Request(environ, charset='utf8'). If you
171 subclass ``Request`` you can also set ``charset`` as a class-level
172 attribute.
6ff6557 @ianb Allow arbitrary attributes to be set on the Request object, and store…
ianb authored
173
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
174 If it is set, then ``req.POST``, ``req.GET``, ``req.params``, and
175 ``req.cookies`` will contain unicode strings. Each has a
176 corresponding ``req.str_*`` (like ``req.str_POST``) that is always
177 ``str`` and never unicode.
6ff6557 @ianb Allow arbitrary attributes to be set on the Request object, and store…
ianb authored
178
75e57d5 @ianb response documentation
ianb authored
179 Response
180 ========
181
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
182 The response object looks a lot like the request object, though with
183 some differences. The request object wraps a single ``environ``
184 object; the response object has three fundamental parts (based on
185 WSGI):
186
187 ``response.status``:
188 The response code plus message, like ``'200 OK'``. To set the
bf89ec5 @ianb Change Response.status_int to Response.status_code (while still suppo…
ianb authored
189 code without the reason, use ``response.status_code = 200``.
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
190
191 ``response.headerlist``:
192 A list of all the headers, like ``[('Content-Type',
193 'text/html')]``. There's a case-insensitive `dictionary-like
194 object`_ in ``response.headers`` that also allows you to access
195 these same headers.
196
197 ``response.app_iter``:
198 An iterable (such as a list or generator) that will produce the
199 content of the response. This is also accessible as
200 ``response.body`` (a string), ``response.unicode_body`` (a
201 unicode object, informed by ``response.charset``), and
202 ``response.body_file`` (a file-like object; writing to it appends
203 to ``app_iter``).
204
205 Everything else in the object derives from this underlying state.
206 Here's the highlights:
207
208 ``response.content_type``:
209 The content type *not* including the ``charset`` parameter.
210 Typical use: ``response.content_type = 'text/html'``. You can
211 subclass ``Response`` and add a class-level attribute
212 ``default_content_type`` to set this automatically on
213 instantiation.
214
215 ``response.charset``:
216 The ``charset`` parameter of the content-type, it also informs
217 encoding in ``response.unicode_body``.
218 ``response.content_type_params`` is a dictionary of all the
219 parameters.
220
221 ``response.request``:
222 This optional attribute can point to the request object associated
223 with this response object.
224
8cdb43d @ianb Add multidict section
ianb authored
225 ``response.set_cookie(key, value, max_age=None, path='/', domain=None, secure=None, httponly=False, version=None, comment=None)``:
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
226 Set a cookie. The keyword arguments control the various cookie
3db67b7 @ianb added note about max_age
ianb authored
227 parameters. The ``max_age`` argument is the length for the cookie
228 to live in seconds (you may also use a timedelta object). The
229 `Expires`` key will also be set based on the value of ``max_age``.
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
230
231 ``response.delete_cookie(key, path='/', domain=None)``:
232 Delete a cookie from the client. This sets ``max_age`` to 0 and
233 the cookie value to ``''``.
234
235 ``response.cache_expires(seconds=0)``:
236 This makes this response cachable for the given number of seconds,
237 or if ``seconds`` is 0 then the response is uncacheable (this also
238 sets the ``Expires`` header).
239
240 ``response(environ, start_response)``: The response object is a WSGI
241 application. As an application, it acts according to how you
242 creat it. It *can* do conditional responses if you pass
243 ``conditional_response=True`` when instantiating (or set that
244 attribute later). It can also do HEAD and Range requests.
e6bad79 @ianb Allow Response() constructor to take any keyword arguments
ianb authored
245
75e57d5 @ianb response documentation
ianb authored
246 Headers
8cdb43d @ianb Add multidict section
ianb authored
247 -------
613ad0f @ianb Added Response.body_file
ianb authored
248
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
249 Like the request, most HTTP response headers are available as
250 properties. These are parsed, so you can do things like
251 ``response.last_modified = os.path.getmtime(filename)``.
613ad0f @ianb Added Response.body_file
ianb authored
252
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
253 The details are available in the `extracted Response documentation
254 <class-webob.Response.html>`_.
845744b @ianb changed to .. code-block::
ianb authored
255
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
256 Instantiating the Response
8cdb43d @ianb Add multidict section
ianb authored
257 --------------------------
75e57d5 @ianb response documentation
ianb authored
258
35acb1d @ianb Note Sergey in the docs/etc
ianb authored
259 Of course most of the time you just want to *make* a response.
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
260 Generally any attribute of the response can be passed in as a keyword
261 argument to the class; e.g.:
845744b @ianb changed to .. code-block::
ianb authored
262
54bd1f7 @ianb sphinx-ify
ianb authored
263 .. code-block:: python
75e57d5 @ianb response documentation
ianb authored
264
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
265 response = Response(body='hello world!', content_type='text/plain')
75e57d5 @ianb response documentation
ianb authored
266
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
267 The status defaults to ``'200 OK'``. The content_type does not
268 default to anything, though if you subclass ``Response`` and set
269 ``default_content_type`` you can override this behavior.
75e57d5 @ianb response documentation
ianb authored
270
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
271 Exceptions
272 ==========
75e57d5 @ianb response documentation
ianb authored
273
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
274 To facilitate error responses like 404 Not Found, the module
275 ``webob.exc`` contains classes for each kind of error response. These
276 include boring but appropriate error bodies.
75e57d5 @ianb response documentation
ianb authored
277
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
278 Each class is named ``webob.exc.HTTP*``, where ``*`` is the reason for
279 the error. For instance, ``webob.exc.HTTPNotFound``. It subclasses
280 ``Response``, so you can manipulate the instances in the same way. A
281 typical example is:
845744b @ianb changed to .. code-block::
ianb authored
282
54bd1f7 @ianb sphinx-ify
ianb authored
283 .. code-block:: python
75e57d5 @ianb response documentation
ianb authored
284
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
285 response = HTTPNotFound('There is no such resource')
286 # or:
287 response = HTTPMovedPermanently(location=new_url)
f8533a0 @ianb add html_escape to webob; add a exc module, from paste.httpexceptions
ianb authored
288
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
289 You can use this like:
f8533a0 @ianb add html_escape to webob; add a exc module, from paste.httpexceptions
ianb authored
290
54bd1f7 @ianb sphinx-ify
ianb authored
291 .. code-block:: python
f8533a0 @ianb add html_escape to webob; add a exc module, from paste.httpexceptions
ianb authored
292
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
293 try:
294 ... stuff ...
700240d @maluke drop python 2.4 compatibility
maluke authored
295 raise HTTPNotFound('No such resource')
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
296 except HTTPException, e:
297 return e(environ, start_response)
f8533a0 @ianb add html_escape to webob; add a exc module, from paste.httpexceptions
ianb authored
298
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
299 The exceptions are still WSGI applications, but you cannot set
300 attributes like ``content_type``, ``charset``, etc. on these exception
301 objects.
f8533a0 @ianb add html_escape to webob; add a exc module, from paste.httpexceptions
ianb authored
302
9fb21d1 @ianb fix up some links, text
ianb authored
303 Multidict
304 =========
8cdb43d @ianb Add multidict section
ianb authored
305
306 Several parts of WebOb use a "multidict"; this is a dictionary where a
307 key can have multiple values. The quintessential example is a query
308 string like ``?pref=red&pref=blue``; the ``pref`` variable has two
309 values: ``red`` and ``blue``.
310
311 In a multidict, when you do ``request.GET['pref']`` you'll get back
312 only ``'blue'`` (the last value of ``pref``). Sometimes returning a
313 string, and sometimes returning a list, is the cause of frequent
314 exceptions. If you want *all* the values back, use
315 ``request.GET.getall('pref')``. If you want to be sure there is *one
316 and only one* value, use ``request.GET.getone('pref')``, which will
317 raise an exception if there is zero or more than one value for
318 ``pref``.
319
320 When you use operations like ``request.GET.items()`` you'll get back
321 something like ``[('pref', 'red'), ('pref', 'blue')]``. All the
322 key/value pairs will show up. Similarly ``request.GET.keys()``
323 returns ``['pref', 'pref']``. Multidict is a view on a list of
324 tuples; all the keys are ordered, and all the values are ordered.
325
4d6fb8e @ianb Refactor documentation some; move the very expicit stuff off to the s…
ianb authored
326 Example
327 =======
20f61a4 @ianb Fixed some bugs in byterange. Fixed a bug in __delattr__, which brok…
ianb authored
328
e186436 @maluke trying to verify docs.webob.org in google webmaster tools
maluke authored
329 The `file-serving example <file-example.html>`_ shows how to do more
54bd1f7 @ianb sphinx-ify
ianb authored
330 advanced HTTP techniques, while the `comment middleware example
331 <comment-example.html>`_ shows middleware. For applications it's more
332 reasonable to use WebOb in the context of a larger framework. `Pylons
e9d3b02 @pjenvey WebOb not optional in Pylons 0.9.7
pjenvey authored
333 <http://pylonshq.com>`_ uses WebOb in 0.9.7+.
e186436 @maluke trying to verify docs.webob.org in google webmaster tools
maluke authored
334
335 .. meta::
336 :google-site-verification: 1oDd59jXPaC0wzgPn3g6cFMI-QvEHjkh8-2rlZeXqwc
Something went wrong with that request. Please try again.