File: index.txt

package info (click to toggle)
python-webob 1%3A1.8.5-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,664 kB
  • sloc: python: 21,344; makefile: 171
file content (337 lines) | stat: -rw-r--r-- 12,188 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
.. _index:

.. module:: webob

.. toctree::
   :hidden:

   self

WebOb
+++++

WebOb provides objects for HTTP requests and responses.  Specifically
it does this by wrapping the `WSGI <https://wsgi.readthedocs.io/en/latest/>`_ request
environment and response status/headers/app_iter(body).

The request and response objects provide many conveniences for parsing HTTP
request and forming HTTP responses.  Both objects are read/write: as a result,
WebOb is also a nice way to create HTTP requests and parse HTTP responses;
however, we won't cover that use case in this document.  The :ref:`reference
documentation <reference>` shows many examples of creating requests.

.. toctree::
   :maxdepth: 2

   reference
   differences
   license


API Documentation
=================

Reference material for every public API exposed by WebOb:

.. toctree::
   :maxdepth: 1
   :glob:

   api/*


.. _experimental-api:

Experimental API
================

There are a variety of features that are considered experimental in WebOb,
these features may change without any notice in future versions of WebOb, or be
removed entirely. If you are relying on these features, please pin your version
of WebOb and carefully watch for changes.

.. toctree::
   :maxdepth: 1
   :glob:

   experimental/*


Request
=======

The request object is a wrapper around the `WSGI environ dictionary
<https://www.python.org/dev/peps/pep-0333/#environ-variables>`_.  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 and interesting attributes of a request object are
the following:

 - :attr:`req.method <webob.request.BaseRequest.method>`
    The request method, e.g., ``GET``, ``POST``, ``PUT``.

 - :attr:`req.GET <webob.request.BaseRequest.GET>`
    A :mod:`dictionary-like object <webob.multidict>` with all the
    variables in the query string.

 - :attr:`req.POST <webob.request.BaseRequest.POST>`
    A :mod:`dictionary-like object <webob.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.

 - :attr:`req.params <webob.request.BaseRequest.params>`:
    A :mod:`dictionary-like object <webob.multidict>` with a
    combination of everything in ``req.GET`` and ``req.POST``.

 - :attr:`req.body <webob.request.BaseRequest.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.

 - :attr:`req.cookies <webob.request.BaseRequest.cookies>`:
    A simple dictionary of all the cookies.

 - :attr:`req.headers <webob.request.BaseRequest.headers>`:
    A dictionary of all the headers. This dictionary is case-insensitive.

Also for standard HTTP request headers, there are usually attributes, e.g.,
:attr:`req.accept_language <webob.request.BaseRequest.accept_language>`,
:attr:`req.content_length <webob.request.BaseRequest.content_length>`, and
:attr:`req.user_agent <webob.request.BaseRequest.user_agent>`. These properties
expose the *parsed* form of each header, for whatever parsing makes sense. For
instance, :attr:`req.if_modified_since
<webob.request.BaseRequest.if_modified_since>` returns a
:class:`~datetime.datetime` object (or ``None`` if the header is was not
provided). Details are in the :mod:`Request object API documentation
<webob.request>`.

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-root/doc?article_id=10``, where the application
is mounted at ``http://localhost/app-root``.

 - :attr:`req.url <webob.request.BaseRequest.url>`:
    The full request URL, with query string, e.g.,
    ``'http://localhost/app-root/doc?article_id=10'``.

 - :attr:`req.application_url <webob.request.BaseRequest.application_url>`:
    The URL of the application (just the ``SCRIPT_NAME`` portion of the
    path, not ``PATH_INFO``), e.g., ``'http://localhost/app-root'``.

 - :attr:`req.host_url <webob.request.BaseRequest.host_url>`:
    The URL with the host, e.g., ``'http://localhost'``.

 - :func:`req.relative_url(url, to_application=False) <webob.request.BaseRequest.relative_url>`:
    Gives a URL, relative to the current URL.  If ``to_application``
    is True, then the URL is resolved relative to ``req.application_url``.

Methods
-------

There are several methods in :class:`~webob.request.Request` but only a few you'll use
often:

 - :func:`Request.blank(uri) <webob.request.BaseRequest.blank>`:
    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).

 - :func:`req.get_response(wsgi_application) <webob.request.BaseRequest.get_response>`:
    This method calls the given WSGI application with this request,
    and returns a `Response`_ object.  You can also use this for
    subrequests or testing.

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.

Response
========

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

 - :attr:`response.status <webob.response.Response.status>`:
    The response code plus message, like ``'200 OK'``.  To set the code without
    the reason, use ``response.status_code = 200``.

 - :attr:`response.headerlist <webob.response.Response.headerlist>`:
    A list of all the headers, like ``[('Content-Type', 'text/html')]``.
    There's a case-insensitive :mod:`dictionary-like object <webob.multidict>` in
    ``response.headers`` that also allows you to access these same headers.

 - :attr:`response.app_iter <webob.response.Response.app_iter>`:
    An iterable (such as a list or generator) that will produce the content of
    the response.  This is also accessible as ``response.body`` (a string),
    ``response.unicode_body`` (a unicode object, informed by
    ``response.charset``), and ``response.body_file`` (a file-like object;
    writing to it appends to ``app_iter``).

Everything else in the object derives from this underlying state.
Here are the highlights:

 - :attr:`response.content_type <webob.response.Response.content_type>`
    The content type *not* including the ``charset`` parameter.  Typical use:
    ``response.content_type = 'text/html'``.  You can subclass ``Response`` and
    add a class-level attribute ``default_content_type`` to set this
    automatically on instantiation.

 - :attr:`response.charset <webob.response.Response.charset>`
    The ``charset`` parameter of the content-type, it also informs encoding in
    ``response.unicode_body``.  ``response.content_type_params`` is a
    dictionary of all the parameters.

 - :func:`response.set_cookie(name=None, value='', max_age=None, ...) <webob.response.Response.set_cookie>`
    Set a cookie.  The keyword arguments control the various cookie parameters.
    The ``max_age`` argument is the length for the cookie to live in seconds
    (you may also use a timedelta object).

 - :func:`response.delete_cookie(name, ...) <webob.response.Response.delete_cookie>`
    Delete a cookie from the client.  This sets ``max_age`` to 0 and the cookie
    value to ``''``.

 - :func:`response.cache_expires(seconds=0) <webob.response.Response.cache_expires>`
    This makes this response cacheable for the given number of seconds, or if
    ``seconds`` is 0 then the response is uncacheable (this also sets the
    ``Expires`` header).

 - :func:`response(environ, start_response) <webob.response.Response.__call__>`
    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=True`` when instantiating (or set that
    attribute later). It can also do HEAD and Range requests.

Headers
-------

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

.. seealso::

   The :class:`~webob.response.Response` object documentation for further
   information.

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

.. code-block:: python

  response = Response(text='hello world!', content_type='text/plain')

The status defaults to ``'200 OK'``. The ``content_type`` defaults to
``default_content_type`` which is set to ``text/html``, although if you
subclass ``Response`` and set ``default_content_type``, you can override this
behavior.

Exceptions
==========

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:

.. code-block:: python

    response = HTTPNotFound('There is no such resource')
    # or:
    response = HTTPMovedPermanently(location=new_url)

You can use this like:

.. code-block:: python

    try:
        # ... stuff ...
        raise HTTPNotFound('No such resource')
    except HTTPException, e:
        return e(environ, start_response)

Example
=======

The `file-serving example <file-example>`_ shows how to do more
advanced HTTP techniques, while the `comment middleware example
<comment-example>`_ shows middleware.  For applications, it's more
reasonable to use WebOb in the context of a larger framework.  `Pyramid
<https://trypyramid.com>`_, and its predecessor `Pylons
<https://docs.pylonsproject.org/projects/pylons-webframework/en/latest/>`_,
both use WebOb.

.. toctree::
   :maxdepth: 1

   file-example
   wiki-example
   comment-example
   jsonrpc-example
   do-it-yourself

Change History
==============

.. toctree::
   :maxdepth: 1

   whatsnew-1.5
   whatsnew-1.6
   whatsnew-1.7
   whatsnew-1.8
   changes

Status and License
==================

WebOb is an extraction and refinement of pieces from `Paste
<https://pypi.python.org/pypi/Paste>`_.  It is under active development on `GitHub
<https://github.com/pylons/webob>`_. It was originally written by `Ian Bicking
<http://www.ianbicking.org/>`_, and is maintained by the `Pylons Project
<https://pylonsproject.org/>`_.

You can clone the source code with:

.. code-block:: bash

    $ git clone https://github.com/Pylons/webob.git

Report issues on the `issue tracker <https://github.com/Pylons/webob/issues>`_.

If you've got questions that aren't answered by this documentation, contact the
`pylons-discuss mail list
<https://groups.google.com/forum/#!forum/pylons-discuss>`_ or join the
`#pyramid IRC channel <https://webchat.freenode.net/?channels=pyramid>`_.

WebOb is released under an :doc:`MIT-style license <license>`.