PageRenderTime 54ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/pyramid/request.py

https://gitlab.com/goolic/pyramid
Python | 332 lines | 268 code | 23 blank | 41 comment | 10 complexity | fb082ddb869f2dc9aac4874a2236859d MD5 | raw file
  1. from collections import deque
  2. import json
  3. from zope.interface import implementer
  4. from zope.interface.interface import InterfaceClass
  5. from webob import BaseRequest
  6. from pyramid.interfaces import (
  7. IRequest,
  8. IRequestExtensions,
  9. IResponse,
  10. ISessionFactory,
  11. )
  12. from pyramid.compat import (
  13. text_,
  14. bytes_,
  15. native_,
  16. iteritems_,
  17. )
  18. from pyramid.decorator import reify
  19. from pyramid.i18n import LocalizerRequestMixin
  20. from pyramid.response import Response, _get_response_factory
  21. from pyramid.security import (
  22. AuthenticationAPIMixin,
  23. AuthorizationAPIMixin,
  24. )
  25. from pyramid.url import URLMethodsMixin
  26. from pyramid.util import (
  27. InstancePropertyHelper,
  28. InstancePropertyMixin,
  29. )
  30. class TemplateContext(object):
  31. pass
  32. class CallbackMethodsMixin(object):
  33. @reify
  34. def finished_callbacks(self):
  35. return deque()
  36. @reify
  37. def response_callbacks(self):
  38. return deque()
  39. def add_response_callback(self, callback):
  40. """
  41. Add a callback to the set of callbacks to be called by the
  42. :term:`router` at a point after a :term:`response` object is
  43. successfully created. :app:`Pyramid` does not have a
  44. global response object: this functionality allows an
  45. application to register an action to be performed against the
  46. response once one is created.
  47. A 'callback' is a callable which accepts two positional
  48. parameters: ``request`` and ``response``. For example:
  49. .. code-block:: python
  50. :linenos:
  51. def cache_callback(request, response):
  52. 'Set the cache_control max_age for the response'
  53. response.cache_control.max_age = 360
  54. request.add_response_callback(cache_callback)
  55. Response callbacks are called in the order they're added
  56. (first-to-most-recently-added). No response callback is
  57. called if an exception happens in application code, or if the
  58. response object returned by :term:`view` code is invalid.
  59. All response callbacks are called *after* the tweens and
  60. *before* the :class:`pyramid.events.NewResponse` event is sent.
  61. Errors raised by callbacks are not handled specially. They
  62. will be propagated to the caller of the :app:`Pyramid`
  63. router application.
  64. .. seealso::
  65. See also :ref:`using_response_callbacks`.
  66. """
  67. self.response_callbacks.append(callback)
  68. def _process_response_callbacks(self, response):
  69. callbacks = self.response_callbacks
  70. while callbacks:
  71. callback = callbacks.popleft()
  72. callback(self, response)
  73. def add_finished_callback(self, callback):
  74. """
  75. Add a callback to the set of callbacks to be called
  76. unconditionally by the :term:`router` at the very end of
  77. request processing.
  78. ``callback`` is a callable which accepts a single positional
  79. parameter: ``request``. For example:
  80. .. code-block:: python
  81. :linenos:
  82. import transaction
  83. def commit_callback(request):
  84. '''commit or abort the transaction associated with request'''
  85. if request.exception is not None:
  86. transaction.abort()
  87. else:
  88. transaction.commit()
  89. request.add_finished_callback(commit_callback)
  90. Finished callbacks are called in the order they're added (
  91. first- to most-recently- added). Finished callbacks (unlike
  92. response callbacks) are *always* called, even if an exception
  93. happens in application code that prevents a response from
  94. being generated.
  95. The set of finished callbacks associated with a request are
  96. called *very late* in the processing of that request; they are
  97. essentially the last thing called by the :term:`router`. They
  98. are called after response processing has already occurred in a
  99. top-level ``finally:`` block within the router request
  100. processing code. As a result, mutations performed to the
  101. ``request`` provided to a finished callback will have no
  102. meaningful effect, because response processing will have
  103. already occurred, and the request's scope will expire almost
  104. immediately after all finished callbacks have been processed.
  105. Errors raised by finished callbacks are not handled specially.
  106. They will be propagated to the caller of the :app:`Pyramid`
  107. router application.
  108. .. seealso::
  109. See also :ref:`using_finished_callbacks`.
  110. """
  111. self.finished_callbacks.append(callback)
  112. def _process_finished_callbacks(self):
  113. callbacks = self.finished_callbacks
  114. while callbacks:
  115. callback = callbacks.popleft()
  116. callback(self)
  117. @implementer(IRequest)
  118. class Request(
  119. BaseRequest,
  120. URLMethodsMixin,
  121. CallbackMethodsMixin,
  122. InstancePropertyMixin,
  123. LocalizerRequestMixin,
  124. AuthenticationAPIMixin,
  125. AuthorizationAPIMixin,
  126. ):
  127. """
  128. A subclass of the :term:`WebOb` Request class. An instance of
  129. this class is created by the :term:`router` and is provided to a
  130. view callable (and to other subsystems) as the ``request``
  131. argument.
  132. The documentation below (save for the ``add_response_callback`` and
  133. ``add_finished_callback`` methods, which are defined in this subclass
  134. itself, and the attributes ``context``, ``registry``, ``root``,
  135. ``subpath``, ``traversed``, ``view_name``, ``virtual_root`` , and
  136. ``virtual_root_path``, each of which is added to the request by the
  137. :term:`router` at request ingress time) are autogenerated from the WebOb
  138. source code used when this documentation was generated.
  139. Due to technical constraints, we can't yet display the WebOb
  140. version number from which this documentation is autogenerated, but
  141. it will be the 'prevailing WebOb version' at the time of the
  142. release of this :app:`Pyramid` version. See
  143. http://webob.org/ for further information.
  144. """
  145. exception = None
  146. exc_info = None
  147. matchdict = None
  148. matched_route = None
  149. request_iface = IRequest
  150. ResponseClass = Response
  151. @reify
  152. def tmpl_context(self):
  153. # docs-deprecated template context for Pylons-like apps; do not
  154. # remove.
  155. return TemplateContext()
  156. @reify
  157. def session(self):
  158. """ Obtain the :term:`session` object associated with this
  159. request. If a :term:`session factory` has not been registered
  160. during application configuration, a
  161. :class:`pyramid.exceptions.ConfigurationError` will be raised"""
  162. factory = self.registry.queryUtility(ISessionFactory)
  163. if factory is None:
  164. raise AttributeError(
  165. 'No session factory registered '
  166. '(see the Sessions chapter of the Pyramid documentation)')
  167. return factory(self)
  168. @reify
  169. def response(self):
  170. """This attribute is actually a "reified" property which returns an
  171. instance of the :class:`pyramid.response.Response`. class. The
  172. response object returned does not exist until this attribute is
  173. accessed. Subsequent accesses will return the same Response object.
  174. The ``request.response`` API is used by renderers. A render obtains
  175. the response object it will return from a view that uses that renderer
  176. by accessing ``request.response``. Therefore, it's possible to use the
  177. ``request.response`` API to set up a response object with "the
  178. right" attributes (e.g. by calling ``request.response.set_cookie()``)
  179. within a view that uses a renderer. Mutations to this response object
  180. will be preserved in the response sent to the client."""
  181. response_factory = _get_response_factory(self.registry)
  182. return response_factory(self)
  183. def is_response(self, ob):
  184. """ Return ``True`` if the object passed as ``ob`` is a valid
  185. response object, ``False`` otherwise."""
  186. if ob.__class__ is Response:
  187. return True
  188. registry = self.registry
  189. adapted = registry.queryAdapterOrSelf(ob, IResponse)
  190. if adapted is None:
  191. return False
  192. return adapted is ob
  193. @property
  194. def json_body(self):
  195. return json.loads(text_(self.body, self.charset))
  196. def route_request_iface(name, bases=()):
  197. # zope.interface treats the __name__ as the __doc__ and changes __name__
  198. # to None for interfaces that contain spaces if you do not pass a
  199. # nonempty __doc__ (insane); see
  200. # zope.interface.interface.Element.__init__ and
  201. # https://github.com/Pylons/pyramid/issues/232; as a result, always pass
  202. # __doc__ to the InterfaceClass constructor.
  203. iface = InterfaceClass('%s_IRequest' % name, bases=bases,
  204. __doc__="route_request_iface-generated interface")
  205. # for exception view lookups
  206. iface.combined = InterfaceClass(
  207. '%s_combined_IRequest' % name,
  208. bases=(iface, IRequest),
  209. __doc__='route_request_iface-generated combined interface')
  210. return iface
  211. def add_global_response_headers(request, headerlist):
  212. def add_headers(request, response):
  213. for k, v in headerlist:
  214. response.headerlist.append((k, v))
  215. request.add_response_callback(add_headers)
  216. def call_app_with_subpath_as_path_info(request, app):
  217. # Copy the request. Use the source request's subpath (if it exists) as
  218. # the new request's PATH_INFO. Set the request copy's SCRIPT_NAME to the
  219. # prefix before the subpath. Call the application with the new request
  220. # and return a response.
  221. #
  222. # Postconditions:
  223. # - SCRIPT_NAME and PATH_INFO are empty or start with /
  224. # - At least one of SCRIPT_NAME or PATH_INFO are set.
  225. # - SCRIPT_NAME is not '/' (it should be '', and PATH_INFO should
  226. # be '/').
  227. environ = request.environ
  228. script_name = environ.get('SCRIPT_NAME', '')
  229. path_info = environ.get('PATH_INFO', '/')
  230. subpath = list(getattr(request, 'subpath', ()))
  231. new_script_name = ''
  232. # compute new_path_info
  233. new_path_info = '/' + '/'.join([native_(x.encode('utf-8'), 'latin-1')
  234. for x in subpath])
  235. if new_path_info != '/': # don't want a sole double-slash
  236. if path_info != '/': # if orig path_info is '/', we're already done
  237. if path_info.endswith('/'):
  238. # readd trailing slash stripped by subpath (traversal)
  239. # conversion
  240. new_path_info += '/'
  241. # compute new_script_name
  242. workback = (script_name + path_info).split('/')
  243. tmp = []
  244. while workback:
  245. if tmp == subpath:
  246. break
  247. el = workback.pop()
  248. if el:
  249. tmp.insert(0, text_(bytes_(el, 'latin-1'), 'utf-8'))
  250. # strip all trailing slashes from workback to avoid appending undue slashes
  251. # to end of script_name
  252. while workback and (workback[-1] == ''):
  253. workback = workback[:-1]
  254. new_script_name = '/'.join(workback)
  255. new_request = request.copy()
  256. new_request.environ['SCRIPT_NAME'] = new_script_name
  257. new_request.environ['PATH_INFO'] = new_path_info
  258. return new_request.get_response(app)
  259. def apply_request_extensions(request, extensions=None):
  260. """Apply request extensions (methods and properties) to an instance of
  261. :class:`pyramid.interfaces.IRequest`. This method is dependent on the
  262. ``request`` containing a properly initialized registry.
  263. After invoking this method, the ``request`` should have the methods
  264. and properties that were defined using
  265. :meth:`pyramid.config.Configurator.add_request_method`.
  266. """
  267. if extensions is None:
  268. extensions = request.registry.queryUtility(IRequestExtensions)
  269. if extensions is not None:
  270. for name, fn in iteritems_(extensions.methods):
  271. method = fn.__get__(request, request.__class__)
  272. setattr(request, name, method)
  273. InstancePropertyHelper.apply_properties(
  274. request, extensions.descriptors)