Michael Merickel
2018-10-04 c314e31223307d7fd739e0bc41519ae6d1d323d3
commit | author | age
844e98 1 .. _request_module:
CM 2
9c3b27 3 :mod:`pyramid.request`
844e98 4 ---------------------------
CM 5
9c3b27 6 .. module:: pyramid.request
844e98 7
CM 8 .. autoclass:: Request
9    :members:
10    :inherited-members:
79a11c 11    :exclude-members: add_response_callback, add_finished_callback,
MM 12                      route_url, route_path, current_route_url,
13                      current_route_path, static_url, static_path,
ee632c 14                      model_url, resource_url, resource_path, set_property, 
0184b5 15                      effective_principals, authenticated_userid,
bc0925 16                      unauthenticated_userid, has_permission,
MM 17                      invoke_exception_view
844e98 18
CM 19    .. attribute:: context
20
21      The :term:`context` will be available as the ``context``
22      attribute of the :term:`request` object.  It will be the context
23      object implied by the current request.  See
24      :ref:`traversal_chapter` for information about context objects.
25
26    .. attribute:: registry
27
28      The :term:`application registry` will be available as the
29      ``registry`` attribute of the :term:`request` object.  See
30      :ref:`zca_chapter` for more information about the application
31      registry.
32
33    .. attribute:: root
34
35       The :term:`root` object will be available as the ``root``
92c3e5 36       attribute of the :term:`request` object.  It will be the resource
844e98 37       object at which traversal started (the root).  See
CM 38       :ref:`traversal_chapter` for information about root objects.
39
40    .. attribute:: subpath
41
42       The traversal :term:`subpath` will be available as the
43       ``subpath`` attribute of the :term:`request` object.  It will
44       be a sequence containing zero or more elements (which will be
45       Unicode objects).  See :ref:`traversal_chapter` for information
46       about the subpath.
47
48    .. attribute:: traversed
49
50       The "traversal path" will be available as the ``traversed``
51       attribute of the :term:`request` object.  It will be a sequence
52       representing the ordered set of names that were used to
53       traverse to the :term:`context`, not including the view name or
54       subpath.  If there is a virtual root associated with the
55       request, the virtual root path is included within the traversal
56       path.  See :ref:`traversal_chapter` for more information.
57
58    .. attribute:: view_name
59
60       The :term:`view name` will be available as the ``view_name``
61       attribute of the :term:`request` object.  It will be a single
62       string (possibly the empty string if we're rendering a default
63       view).  See :ref:`traversal_chapter` for information about view
64       names.
65
66    .. attribute:: virtual_root
67
68       The :term:`virtual root` will be available as the
69       ``virtual_root`` attribute of the :term:`request` object.  It
70       will be the virtual root object implied by the current request.
71       See :ref:`vhosting_chapter` for more information about virtual
72       roots.
73
74    .. attribute:: virtual_root_path
75
76       The  :term:`virtual  root`  *path*  will be  available  as  the
77       ``virtual_root_path`` attribute  of the :term:`request` object.
78       It will  be a  sequence representing the  ordered set  of names
79       that were  used to  traverse to the  virtual root  object.  See
80       :ref:`vhosting_chapter`  for  more  information  about  virtual
81       roots.
82
81d3b5 83    .. attribute:: exception
CM 84
85      If an exception was raised by a :term:`root factory` or a
86      :term:`view callable`, or at various other points where
fd5ae9 87      :app:`Pyramid` executes user-defined code during the
81d3b5 88      processing of a request, the exception object which was caught
CM 89      will be available as the ``exception`` attribute of the request
90      within a :term:`exception view`, a :term:`response callback` or a
91      :term:`finished callback`.  If no exception occurred, the value
92      of ``request.exception`` will be ``None`` within response and
93      finished callbacks.
94
95a379 95    .. attribute:: exc_info
CM 96
97      If an exception was raised by a :term:`root factory` or a :term:`view
98      callable`, or at various other points where :app:`Pyramid` executes
99      user-defined code during the processing of a request, result of
100      ``sys.exc_info()`` will be available as the ``exc_info`` attribute of
101      the request within a :term:`exception view`, a :term:`response callback`
102      or a :term:`finished callback`.  If no exception occurred, the value of
103      ``request.exc_info`` will be ``None`` within response and finished
104      callbacks.
105
a7b1a9 106    .. attribute:: response
CM 107
108      This attribute is actually a "reified" property which returns an
109      instance of the :class:`pyramid.response.Response` class.  The response
110      object returned does not exist until this attribute is accessed.  Once
111      it is accessed, subsequent accesses to this request object will return
112      the same :class:`~pyramid.response.Response` object.
113
b330c7 114      The ``request.response`` API can is used by renderers.  A render obtains
CM 115      the response object it will return from a view that uses that renderer
116      by accessing ``request.response``.  Therefore, it's possible to use the
a7b1a9 117      ``request.response`` API to set up a response object with "the right"
CM 118      attributes (e.g. by calling ``request.response.set_cookie(...)`` or
119      ``request.response.content_type = 'text/plain'``, etc) within a view
120      that uses a renderer.  For example, within a view that uses a
6717cc 121      :term:`renderer`::
a7b1a9 122
CM 123          response = request.response
124          response.set_cookie('mycookie', 'mine, all mine!')
125          return {'text':'Value that will be used by the renderer'}
126
127      Mutations to this response object will be preserved in the response sent
d868ff 128      to the client after rendering.  For more information about using
CM 129      ``request.response`` in conjunction with a renderer, see
130      :ref:`request_response_attr`.
a7b1a9 131
CM 132      Non-renderer code can also make use of request.response instead of
133      creating a response "by hand".  For example, in view code::
134
135         response = request.response
136         response.body = 'Hello!'
137         response.content_type = 'text/plain'
138         return response
139
6717cc 140      Note that the response in this circumstance is not "global"; it still
CM 141      must be returned from the view code if a renderer is not used.
b330c7 142
04ebd5 143    .. attribute:: session
CM 144
145      If a :term:`session factory` has been configured, this attribute
146      will represent the current user's :term:`session` object.  If a
147      session factory *has not* been configured, requesting the
148      ``request.session`` attribute will cause a
149      :class:`pyramid.exceptions.ConfigurationError` to be raised.
150
4eafaa 151    .. attribute:: matchdict
CM 152
153       If a :term:`route` has matched during this request, this attribute will
154       be a dictionary containing the values matched by the URL pattern
155       associated with the route.  If a route has not matched during this
156       request, the value of this attribute will be ``None``. See
157       :ref:`matchdict`.
158
159    .. attribute:: matched_route
160
161       If a :term:`route` has matched during this request, this attribute will
268e1d 162       be an object representing the route matched by the URL pattern
4eafaa 163       associated with the route.  If a route has not matched during this
CM 164       request, the value of this attribute will be ``None``. See
165       :ref:`matched_route`.
14dc81 166
0184b5 167    .. attribute:: authenticated_userid
CM 168
169       .. versionadded:: 1.5
170
dc3247 171       A property which returns the :term:`userid` of the currently
KOP 172       authenticated user or ``None`` if there is no :term:`authentication
173       policy` in effect or there is no currently authenticated user.  This
174       differs from :attr:`~pyramid.request.Request.unauthenticated_userid`,
175       because the effective authentication policy will have ensured that a
fe83c6 176       record associated with the :term:`userid` exists in persistent storage;
MM 177       if it has not, this value will be ``None``.
0184b5 178
CM 179    .. attribute:: unauthenticated_userid
180
181       .. versionadded:: 1.5
182
183       A property which returns a value which represents the *claimed* (not
dc3247 184       verified) :term:`userid` of the credentials present in the
KOP 185       request. ``None`` if there is no :term:`authentication policy` in effect
186       or there is no user data associated with the current request.  This
187       differs from :attr:`~pyramid.request.Request.authenticated_userid`,
188       because the effective authentication policy will not ensure that a
189       record associated with the :term:`userid` exists in persistent storage.
190       Even if the :term:`userid` does not exist in persistent storage, this
191       value will be the value of the :term:`userid` *claimed* by the request
192       data.
0184b5 193
CM 194    .. attribute:: effective_principals
195
196       .. versionadded:: 1.5
197
198       A property which returns the list of 'effective' :term:`principal`
81719b 199       identifiers for this request.  This list typically includes the
KOP 200       :term:`userid` of the currently authenticated user if a user is
201       currently authenticated, but this depends on the
202       :term:`authentication policy` in effect.  If no :term:`authentication
203       policy` is in effect, this will return a sequence containing only the
204       :attr:`pyramid.security.Everyone` principal.
0184b5 205
db2a03 206    .. method:: invoke_subrequest(request, use_tweens=False)
277b2a 207
23c898 208       .. versionadded:: 1.4a1
37d2c2 209
277b2a 210       Obtain a response object from the Pyramid application based on
CM 211       information in the ``request`` object provided.  The ``request`` object
212       must be an object that implements the Pyramid request interface (such
213       as a :class:`pyramid.request.Request` instance).  If ``use_tweens`` is
214       ``True``, the request will be sent to the :term:`tween` in the tween
215       stack closest to the request ingress.  If ``use_tweens`` is ``False``,
216       the request will be sent to the main router handler, and no tweens will
7259e7 217       be invoked.
CM 218
219       This function also:
277b2a 220         
CM 221       - manages the threadlocal stack (so that
222         :func:`~pyramid.threadlocal.get_current_request` and
223         :func:`~pyramid.threadlocal.get_current_registry` work during a
224         request)
225
226       - Adds a ``registry`` attribute (the current Pyramid registry) and a
64452e 227         ``invoke_subrequest`` attribute (a callable) to the request object it's
277b2a 228         handed.
CM 229
230       - sets request extensions (such as those added via
1f307d 231         :meth:`~pyramid.config.Configurator.add_request_method`) on the
277b2a 232         request it's passed.
CM 233
aaedf5 234       - causes a :class:`~pyramid.events.NewRequest` event to be sent at the
277b2a 235         beginning of request processing.
CM 236
aaedf5 237       - causes a :class:`~pyramid.events.ContextFound` event to be sent
277b2a 238         when a context resource is found.
aaedf5 239
db2a03 240       - Ensures that the user implied by the request passed has the necessary
CM 241         authorization to invoke view callable before calling it.
242
277b2a 243       - Calls any :term:`response callback` functions defined within the
CM 244         request's lifetime if a response is obtained from the Pyramid
245         application.
246
fc477b 247       - causes a :class:`~pyramid.events.NewResponse` event to be sent if a
CM 248         response is obtained.
249
277b2a 250       - Calls any :term:`finished callback` functions defined within the
CM 251         request's lifetime.
252
7259e7 253       ``invoke_subrequest`` isn't *actually* a method of the Request object;
CM 254       it's a callable added when the Pyramid router is invoked, or when a
255       subrequest is invoked.  This means that it's not available for use on a
2033ee 256       request provided by e.g. the ``pshell`` environment.
SP 257
258       .. seealso::
259
260           See also :ref:`subrequest_chapter`.
0184b5 261
bc0925 262    .. automethod:: invoke_exception_view
MM 263
0184b5 264    .. automethod:: has_permission
CM 265
72ad33 266    .. automethod:: add_response_callback
CM 267
268    .. automethod:: add_finished_callback
269
270    .. automethod:: route_url
271
272    .. automethod:: route_path
5c6963 273
CM 274    .. automethod:: current_route_url
72ad33 275
12cef0 276    .. automethod:: current_route_path
CM 277
72ad33 278    .. automethod:: static_url
CM 279
5c6963 280    .. automethod:: static_path
CM 281
282    .. automethod:: resource_url
283
c51896 284    .. automethod:: resource_path
CM 285
6a0602 286    .. attribute:: json_body
b78eff 287
6a0602 288        This property will return the JSON-decoded variant of the request
CM 289        body.  If the request body is not well-formed JSON, or there is no
290        body associated with this request, this property will raise an
2033ee 291        exception.
SP 292        
293        .. seealso::
294        
295            See also :ref:`request_json_body`.
b78eff 296
1b113f 297    .. method:: set_property(callable, name=None, reify=False)
79a11c 298
MM 299        Add a callable or a property descriptor to the request instance.
300
301        Properties, unlike attributes, are lazily evaluated by executing
302        an underlying callable when accessed. They can be useful for
303        adding features to an object without any cost if those features
304        go unused.
305
306        A property may also be reified via the
307        :class:`pyramid.decorator.reify` decorator by setting
308        ``reify=True``, allowing the result of the evaluation to be
309        cached. Thus the value of the property is only computed once for
310        the lifetime of the object.
311
1b113f 312        ``callable`` can either be a callable that accepts the request as
79a11c 313        its single positional parameter, or it can be a property
MM 314        descriptor.
315
1b113f 316        If the ``callable`` is a property descriptor a ``ValueError``
MM 317        will be raised if ``name`` is ``None`` or ``reify`` is ``True``.
79a11c 318
MM 319        If ``name`` is None, the name of the property will be computed
1b113f 320        from the name of the ``callable``.
79a11c 321
MM 322        .. code-block:: python
fcc53a 323            :linenos:
79a11c 324
fcc53a 325            def _connect(request):
SP 326                conn = request.registry.dbsession()
327                def cleanup(request):
328                    # since version 1.5, request.exception is no
329                    # longer eagerly cleared
330                    if request.exception is not None:
331                        conn.rollback()
332                    else:
333                        conn.commit()
334                    conn.close()
335                request.add_finished_callback(cleanup)
336                return conn
79a11c 337
fcc53a 338            @subscriber(NewRequest)
SP 339            def new_request(event):
340                request = event.request
341                request.set_property(_connect, 'db', reify=True)
79a11c 342
MM 343        The subscriber doesn't actually connect to the database, it just
344        provides the API which, when accessed via ``request.db``, will
345        create the connection. Thanks to reify, only one connection is
346        made per-request even if ``request.db`` is accessed many times.
347
348        This pattern provides a way to augment the ``request`` object
349        without having to subclass it, which can be useful for extension
350        authors.
351
1b113f 352        .. versionadded:: 1.3
MM 353
330164 354    .. attribute::  localizer
CM 355
356        A :term:`localizer` which will use the current locale name to
357        translate values.
358
359        .. versionadded:: 1.5
360
361    .. attribute::  locale_name
362
363        The locale name of the current request as computed by the 
364        :term:`locale negotiator`.
365
366        .. versionadded:: 1.5
367
2a1c3f 368 .. note::
CM 369
370    For information about the API of a :term:`multidict` structure (such as
371    that used as ``request.GET``, ``request.POST``, and ``request.params``),
372    see :class:`pyramid.interfaces.IMultiDict`.
373
04cc91 374 .. autofunction:: apply_request_extensions(request)