Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/pyramid/interfaces.py : 99%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from zope.deprecation import deprecated
3from zope.interface import Attribute, Interface
5from pyramid.compat import PY2
7# public API interfaces
10class IContextFound(Interface):
11 """ An event type that is emitted after :app:`Pyramid` finds a
12 :term:`context` object but before it calls any view code. See the
13 documentation attached to :class:`pyramid.events.ContextFound`
14 for more information.
16 .. note::
18 For backwards compatibility with versions of
19 :app:`Pyramid` before 1.0, this event interface can also be
20 imported as :class:`pyramid.interfaces.IAfterTraversal`.
21 """
23 request = Attribute('The request object')
26IAfterTraversal = IContextFound
29class IBeforeTraversal(Interface):
30 """
31 An event type that is emitted after :app:`Pyramid` attempted to find a
32 route but before it calls any traversal or view code. See the documentation
33 attached to :class:`pyramid.events.Routefound` for more information.
34 """
36 request = Attribute('The request object')
39class INewRequest(Interface):
40 """ An event type that is emitted whenever :app:`Pyramid`
41 begins to process a new request. See the documentation attached
42 to :class:`pyramid.events.NewRequest` for more information."""
44 request = Attribute('The request object')
47class INewResponse(Interface):
48 """ An event type that is emitted whenever any :app:`Pyramid`
49 view returns a response. See the
50 documentation attached to :class:`pyramid.events.NewResponse`
51 for more information."""
53 request = Attribute('The request object')
54 response = Attribute('The response object')
57class IApplicationCreated(Interface):
58 """ Event issued when the
59 :meth:`pyramid.config.Configurator.make_wsgi_app` method
60 is called. See the documentation attached to
61 :class:`pyramid.events.ApplicationCreated` for more
62 information.
64 .. note::
66 For backwards compatibility with :app:`Pyramid`
67 versions before 1.0, this interface can also be imported as
68 :class:`pyramid.interfaces.IWSGIApplicationCreatedEvent`.
69 """
71 app = Attribute("Created application")
74IWSGIApplicationCreatedEvent = IApplicationCreated # b /c
77class IResponse(Interface):
78 """ Represents a WSGI response using the WebOb response interface.
79 Some attribute and method documentation of this interface references
80 :rfc:`2616`.
82 This interface is most famously implemented by
83 :class:`pyramid.response.Response` and the HTTP exception classes in
84 :mod:`pyramid.httpexceptions`."""
86 RequestClass = Attribute(
87 """ Alias for :class:`pyramid.request.Request` """
88 )
90 def __call__(environ, start_response):
91 """ :term:`WSGI` call interface, should call the start_response
92 callback and should return an iterable"""
94 accept_ranges = Attribute(
95 """Gets and sets and deletes the Accept-Ranges header. For more
96 information on Accept-Ranges see RFC 2616, section 14.5"""
97 )
99 age = Attribute(
100 """Gets and sets and deletes the Age header. Converts using int.
101 For more information on Age see RFC 2616, section 14.6."""
102 )
104 allow = Attribute(
105 """Gets and sets and deletes the Allow header. Converts using
106 list. For more information on Allow see RFC 2616, Section 14.7."""
107 )
109 app_iter = Attribute(
110 """Returns the app_iter of the response.
112 If body was set, this will create an app_iter from that body
113 (a single-item list)"""
114 )
116 def app_iter_range(start, stop):
117 """ Return a new app_iter built from the response app_iter that
118 serves up only the given start:stop range. """
120 body = Attribute(
121 """The body of the response, as a str. This will read in the entire
122 app_iter if necessary."""
123 )
125 body_file = Attribute(
126 """A file-like object that can be used to write to the body. If you
127 passed in a list app_iter, that app_iter will be modified by writes."""
128 )
130 cache_control = Attribute(
131 """Get/set/modify the Cache-Control header (RFC 2616 section 14.9)"""
132 )
134 cache_expires = Attribute(
135 """ Get/set the Cache-Control and Expires headers. This sets the
136 response to expire in the number of seconds passed when set. """
137 )
139 charset = Attribute("""Get/set the charset (in the Content-Type)""")
141 def conditional_response_app(environ, start_response):
142 """ Like the normal __call__ interface, but checks conditional
143 headers:
145 - If-Modified-Since (304 Not Modified; only on GET, HEAD)
147 - If-None-Match (304 Not Modified; only on GET, HEAD)
149 - Range (406 Partial Content; only on GET, HEAD)"""
151 content_disposition = Attribute(
152 """Gets and sets and deletes the Content-Disposition header.
153 For more information on Content-Disposition see RFC 2616 section
154 19.5.1."""
155 )
157 content_encoding = Attribute(
158 """Gets and sets and deletes the Content-Encoding header. For more
159 information about Content-Encoding see RFC 2616 section 14.11."""
160 )
162 content_language = Attribute(
163 """Gets and sets and deletes the Content-Language header. Converts
164 using list. For more information about Content-Language see RFC 2616
165 section 14.12."""
166 )
168 content_length = Attribute(
169 """Gets and sets and deletes the Content-Length header. For more
170 information on Content-Length see RFC 2616 section 14.17.
171 Converts using int. """
172 )
174 content_location = Attribute(
175 """Gets and sets and deletes the Content-Location header. For more
176 information on Content-Location see RFC 2616 section 14.14."""
177 )
179 content_md5 = Attribute(
180 """Gets and sets and deletes the Content-MD5 header. For more
181 information on Content-MD5 see RFC 2616 section 14.14."""
182 )
184 content_range = Attribute(
185 """Gets and sets and deletes the Content-Range header. For more
186 information on Content-Range see section 14.16. Converts using
187 ContentRange object."""
188 )
190 content_type = Attribute(
191 """Get/set the Content-Type header (or None), without the charset
192 or any parameters. If you include parameters (or ; at all) when
193 setting the content_type, any existing parameters will be deleted;
194 otherwise they will be preserved."""
195 )
197 content_type_params = Attribute(
198 """A dictionary of all the parameters in the content type. This is
199 not a view, set to change, modifications of the dict would not
200 be applied otherwise."""
201 )
203 def copy():
204 """ Makes a copy of the response and returns the copy. """
206 date = Attribute(
207 """Gets and sets and deletes the Date header. For more information on
208 Date see RFC 2616 section 14.18. Converts using HTTP date."""
209 )
211 def delete_cookie(name, path='/', domain=None):
212 """ Delete a cookie from the client. Note that path and domain must
213 match how the cookie was originally set. This sets the cookie to the
214 empty string, and max_age=0 so that it should expire immediately. """
216 def encode_content(encoding='gzip', lazy=False):
217 """ Encode the content with the given encoding (only gzip and
218 identity are supported)."""
220 environ = Attribute(
221 """Get/set the request environ associated with this response,
222 if any."""
223 )
225 etag = Attribute(
226 """ Gets and sets and deletes the ETag header. For more information
227 on ETag see RFC 2616 section 14.19. Converts using Entity tag."""
228 )
230 expires = Attribute(
231 """ Gets and sets and deletes the Expires header. For more
232 information on Expires see RFC 2616 section 14.21. Converts using
233 HTTP date."""
234 )
236 headerlist = Attribute(""" The list of response headers. """)
238 headers = Attribute(""" The headers in a dictionary-like object """)
240 last_modified = Attribute(
241 """ Gets and sets and deletes the Last-Modified header. For more
242 information on Last-Modified see RFC 2616 section 14.29. Converts
243 using HTTP date."""
244 )
246 location = Attribute(
247 """ Gets and sets and deletes the Location header. For more
248 information on Location see RFC 2616 section 14.30."""
249 )
251 def md5_etag(body=None, set_content_md5=False):
252 """ Generate an etag for the response object using an MD5 hash of the
253 body (the body parameter, or self.body if not given). Sets self.etag.
254 If set_content_md5 is True sets self.content_md5 as well """
256 def merge_cookies(resp):
257 """ Merge the cookies that were set on this response with the given
258 resp object (which can be any WSGI application). If the resp is a
259 webob.Response object, then the other object will be modified
260 in-place. """
262 pragma = Attribute(
263 """ Gets and sets and deletes the Pragma header. For more information
264 on Pragma see RFC 2616 section 14.32. """
265 )
267 request = Attribute(
268 """ Return the request associated with this response if any. """
269 )
271 retry_after = Attribute(
272 """ Gets and sets and deletes the Retry-After header. For more
273 information on Retry-After see RFC 2616 section 14.37. Converts
274 using HTTP date or delta seconds."""
275 )
277 server = Attribute(
278 """ Gets and sets and deletes the Server header. For more information
279 on Server see RFC216 section 14.38. """
280 )
282 def set_cookie(
283 name,
284 value='',
285 max_age=None,
286 path='/',
287 domain=None,
288 secure=False,
289 httponly=False,
290 comment=None,
291 expires=None,
292 overwrite=False,
293 ):
294 """ Set (add) a cookie for the response """
296 status = Attribute(""" The status string. """)
298 status_int = Attribute(""" The status as an integer """)
300 unicode_body = Attribute(
301 """ Get/set the unicode value of the body (using the charset of
302 the Content-Type)"""
303 )
305 def unset_cookie(name, strict=True):
306 """ Unset a cookie with the given name (remove it from the
307 response)."""
309 vary = Attribute(
310 """Gets and sets and deletes the Vary header. For more information
311 on Vary see section 14.44. Converts using list."""
312 )
314 www_authenticate = Attribute(
315 """ Gets and sets and deletes the WWW-Authenticate header. For more
316 information on WWW-Authenticate see RFC 2616 section 14.47. Converts
317 using 'parse_auth' and 'serialize_auth'. """
318 )
321class IException(Interface): # not an API
322 """ An interface representing a generic exception """
325class IExceptionResponse(IException, IResponse):
326 """ An interface representing a WSGI response which is also an exception
327 object. Register an exception view using this interface as a ``context``
328 to apply the registered view for all exception types raised by
329 :app:`Pyramid` internally (any exception that inherits from
330 :class:`pyramid.response.Response`, including
331 :class:`pyramid.httpexceptions.HTTPNotFound` and
332 :class:`pyramid.httpexceptions.HTTPForbidden`)."""
334 def prepare(environ):
335 """ Prepares the response for being called as a WSGI application """
338class IDict(Interface):
339 # Documentation-only interface
341 def __contains__(k):
342 """ Return ``True`` if key ``k`` exists in the dictionary."""
344 def __setitem__(k, value):
345 """ Set a key/value pair into the dictionary"""
347 def __delitem__(k):
348 """ Delete an item from the dictionary which is passed to the
349 renderer as the renderer globals dictionary."""
351 def __getitem__(k):
352 """ Return the value for key ``k`` from the dictionary or raise a
353 KeyError if the key doesn't exist"""
355 def __iter__():
356 """ Return an iterator over the keys of this dictionary """
358 def get(k, default=None):
359 """ Return the value for key ``k`` from the renderer dictionary, or
360 the default if no such value exists."""
362 def items():
363 """ Return a list of [(k,v)] pairs from the dictionary """
365 def keys():
366 """ Return a list of keys from the dictionary """
368 def values():
369 """ Return a list of values from the dictionary """
371 if PY2:
373 def iterkeys():
374 """ Return an iterator of keys from the dictionary """
376 def iteritems():
377 """ Return an iterator of (k,v) pairs from the dictionary """
379 def itervalues():
380 """ Return an iterator of values from the dictionary """
382 has_key = __contains__
384 def pop(k, default=None):
385 """ Pop the key k from the dictionary and return its value. If k
386 doesn't exist, and default is provided, return the default. If k
387 doesn't exist and default is not provided, raise a KeyError."""
389 def popitem():
390 """ Pop the item with key k from the dictionary and return it as a
391 two-tuple (k, v). If k doesn't exist, raise a KeyError."""
393 def setdefault(k, default=None):
394 """ Return the existing value for key ``k`` in the dictionary. If no
395 value with ``k`` exists in the dictionary, set the ``default``
396 value into the dictionary under the k name passed. If a value already
397 existed in the dictionary, return it. If a value did not exist in
398 the dictionary, return the default"""
400 def update(d):
401 """ Update the renderer dictionary with another dictionary ``d``."""
403 def clear():
404 """ Clear all values from the dictionary """
407class IBeforeRender(IDict):
408 """
409 Subscribers to this event may introspect and modify the set of
410 :term:`renderer globals` before they are passed to a :term:`renderer`.
411 The event object itself provides a dictionary-like interface for adding
412 and removing :term:`renderer globals`. The keys and values of the
413 dictionary are those globals. For example::
415 from repoze.events import subscriber
416 from pyramid.interfaces import IBeforeRender
418 @subscriber(IBeforeRender)
419 def add_global(event):
420 event['mykey'] = 'foo'
422 .. seealso::
424 See also :ref:`beforerender_event`.
425 """
427 rendering_val = Attribute(
428 'The value returned by a view or passed to a '
429 '``render`` method for this rendering. '
430 'This feature is new in Pyramid 1.2.'
431 )
434class IRendererInfo(Interface):
435 """ An object implementing this interface is passed to every
436 :term:`renderer factory` constructor as its only argument (conventionally
437 named ``info``)"""
439 name = Attribute('The value passed by the user as the renderer name')
440 package = Attribute(
441 'The "current package" when the renderer '
442 'configuration statement was found'
443 )
444 type = Attribute('The renderer type name')
445 registry = Attribute(
446 'The "current" application registry when the ' 'renderer was created'
447 )
448 settings = Attribute(
449 'The deployment settings dictionary related '
450 'to the current application'
451 )
453 def clone():
454 """ Return a shallow copy that does not share any mutable state."""
457class IRendererFactory(Interface):
458 def __call__(info):
459 """ Return an object that implements
460 :class:`pyramid.interfaces.IRenderer`. ``info`` is an
461 object that implements :class:`pyramid.interfaces.IRendererInfo`.
462 """
465class IRenderer(Interface):
466 def __call__(value, system):
467 """ Call the renderer with the result of the
468 view (``value``) passed in and return a result (a string or
469 unicode object useful as a response body). Values computed by
470 the system are passed by the system in the ``system``
471 parameter, which is a dictionary. Keys in the dictionary
472 include: ``view`` (the view callable that returned the value),
473 ``renderer_name`` (the template name or simple name of the
474 renderer), ``context`` (the context object passed to the
475 view), and ``request`` (the request object passed to the
476 view)."""
479class ITemplateRenderer(IRenderer):
480 def implementation():
481 """ Return the object that the underlying templating system
482 uses to render the template; it is typically a callable that
483 accepts arbitrary keyword arguments and returns a string or
484 unicode object """
487deprecated(
488 'ITemplateRenderer',
489 'As of Pyramid 1.5 the, "pyramid.interfaces.ITemplateRenderer" interface '
490 'is scheduled to be removed. It was used by the Mako and Chameleon '
491 'renderers which have been split into their own packages.',
492)
495class IViewMapper(Interface):
496 def __call__(self, object):
497 """ Provided with an arbitrary object (a function, class, or
498 instance), returns a callable with the call signature ``(context,
499 request)``. The callable returned should itself return a Response
500 object. An IViewMapper is returned by
501 :class:`pyramid.interfaces.IViewMapperFactory`."""
504class IViewMapperFactory(Interface):
505 def __call__(self, **kw):
506 """
507 Return an object which implements
508 :class:`pyramid.interfaces.IViewMapper`. ``kw`` will be a dictionary
509 containing view-specific arguments, such as ``permission``,
510 ``predicates``, ``attr``, ``renderer``, and other items. An
511 IViewMapperFactory is used by
512 :meth:`pyramid.config.Configurator.add_view` to provide a plugpoint
513 to extension developers who want to modify potential view callable
514 invocation signatures and response values.
515 """
518class IAuthenticationPolicy(Interface):
519 """ An object representing a Pyramid authentication policy. """
521 def authenticated_userid(request):
522 """ Return the authenticated :term:`userid` or ``None`` if
523 no authenticated userid can be found. This method of the
524 policy should ensure that a record exists in whatever
525 persistent store is used related to the user (the user
526 should not have been deleted); if a record associated with
527 the current id does not exist in a persistent store, it
528 should return ``None``.
530 """
532 def unauthenticated_userid(request):
533 """ Return the *unauthenticated* userid. This method
534 performs the same duty as ``authenticated_userid`` but is
535 permitted to return the userid based only on data present
536 in the request; it needn't (and shouldn't) check any
537 persistent store to ensure that the user record related to
538 the request userid exists.
540 This method is intended primarily a helper to assist the
541 ``authenticated_userid`` method in pulling credentials out
542 of the request data, abstracting away the specific headers,
543 query strings, etc that are used to authenticate the request.
545 """
547 def effective_principals(request):
548 """ Return a sequence representing the effective principals
549 typically including the :term:`userid` and any groups belonged
550 to by the current user, always including 'system' groups such
551 as ``pyramid.security.Everyone`` and
552 ``pyramid.security.Authenticated``.
554 """
556 def remember(request, userid, **kw):
557 """ Return a set of headers suitable for 'remembering' the
558 :term:`userid` named ``userid`` when set in a response. An
559 individual authentication policy and its consumers can
560 decide on the composition and meaning of ``**kw``.
562 """
564 def forget(request):
565 """ Return a set of headers suitable for 'forgetting' the
566 current user on subsequent requests.
568 """
571class IAuthorizationPolicy(Interface):
572 """ An object representing a Pyramid authorization policy. """
574 def permits(context, principals, permission):
575 """ Return an instance of :class:`pyramid.security.Allowed` if any
576 of the ``principals`` is allowed the ``permission`` in the current
577 ``context``, else return an instance of
578 :class:`pyramid.security.Denied`.
579 """
581 def principals_allowed_by_permission(context, permission):
582 """ Return a set of principal identifiers allowed by the
583 ``permission`` in ``context``. This behavior is optional; if you
584 choose to not implement it you should define this method as
585 something which raises a ``NotImplementedError``. This method
586 will only be called when the
587 ``pyramid.security.principals_allowed_by_permission`` API is
588 used."""
591class IMultiDict(IDict): # docs-only interface
592 """
593 An ordered dictionary that can have multiple values for each key. A
594 multidict adds the methods ``getall``, ``getone``, ``mixed``, ``extend``,
595 ``add``, and ``dict_of_lists`` to the normal dictionary interface. A
596 multidict data structure is used as ``request.POST``, ``request.GET``,
597 and ``request.params`` within an :app:`Pyramid` application.
598 """
600 def add(key, value):
601 """ Add the key and value, not overwriting any previous value. """
603 def dict_of_lists():
604 """
605 Returns a dictionary where each key is associated with a list of
606 values.
607 """
609 def extend(other=None, **kwargs):
610 """ Add a set of keys and values, not overwriting any previous
611 values. The ``other`` structure may be a list of two-tuples or a
612 dictionary. If ``**kwargs`` is passed, its value *will* overwrite
613 existing values."""
615 def getall(key):
616 """ Return a list of all values matching the key (may be an empty
617 list) """
619 def getone(key):
620 """ Get one value matching the key, raising a KeyError if multiple
621 values were found. """
623 def mixed():
624 """ Returns a dictionary where the values are either single values,
625 or a list of values when a key/value appears more than once in this
626 dictionary. This is similar to the kind of dictionary often used to
627 represent the variables in a web request. """
630# internal interfaces
633class IRequest(Interface):
634 """ Request type interface attached to all request objects """
637class ITweens(Interface):
638 """ Marker interface for utility registration representing the ordered
639 set of a configuration's tween factories"""
642class IRequestHandler(Interface):
643 """ """
645 def __call__(self, request):
646 """ Must return a tuple of IReqest, IResponse or raise an exception.
647 The ``request`` argument will be an instance of an object that
648 provides IRequest."""
651IRequest.combined = IRequest # for exception view lookups
654class IRequestExtensions(Interface):
655 """ Marker interface for storing request extensions (properties and
656 methods) which will be added to the request object."""
658 descriptors = Attribute(
659 """A list of descriptors that will be added to each request."""
660 )
661 methods = Attribute("""A list of methods to be added to each request.""")
664class IRouteRequest(Interface):
665 """ *internal only* interface used as in a utility lookup to find
666 route-specific interfaces. Not an API."""
669class IAcceptOrder(Interface):
670 """
671 Marker interface for a list of accept headers with the most important
672 first.
674 """
677class IStaticURLInfo(Interface):
678 """ A policy for generating URLs to static assets """
680 def add(config, name, spec, **extra):
681 """ Add a new static info registration """
683 def generate(path, request, **kw):
684 """ Generate a URL for the given path """
686 def add_cache_buster(config, spec, cache_buster):
687 """ Add a new cache buster to a particular set of assets """
690class IResponseFactory(Interface):
691 """ A utility which generates a response """
693 def __call__(request):
694 """ Return a response object implementing IResponse,
695 e.g. :class:`pyramid.response.Response`). It should handle the
696 case when ``request`` is ``None``."""
699class IRequestFactory(Interface):
700 """ A utility which generates a request """
702 def __call__(environ):
703 """ Return an instance of ``pyramid.request.Request``"""
705 def blank(path):
706 """ Return an empty request object (see
707 :meth:`pyramid.request.Request.blank`)"""
710class IViewClassifier(Interface):
711 """ *Internal only* marker interface for views."""
714class IExceptionViewClassifier(Interface):
715 """ *Internal only* marker interface for exception views."""
718class IView(Interface):
719 def __call__(context, request):
720 """ Must return an object that implements IResponse. """
723class ISecuredView(IView):
724 """ *Internal only* interface. Not an API. """
726 def __call_permissive__(context, request):
727 """ Guaranteed-permissive version of __call__ """
729 def __permitted__(context, request):
730 """ Return True if view execution will be permitted using the
731 context and request, False otherwise"""
734class IMultiView(ISecuredView):
735 """ *internal only*. A multiview is a secured view that is a
736 collection of other views. Each of the views is associated with
737 zero or more predicates. Not an API."""
739 def add(view, predicates, order, accept=None, phash=None):
740 """ Add a view to the multiview. """
743class IRootFactory(Interface):
744 def __call__(request):
745 """ Return a root object based on the request """
748class IDefaultRootFactory(Interface):
749 def __call__(request):
750 """ Return the *default* root object for an application """
753class ITraverser(Interface):
754 def __call__(request):
755 """ Return a dictionary with (at least) the keys ``root``,
756 ``context``, ``view_name``, ``subpath``, ``traversed``,
757 ``virtual_root``, and ``virtual_root_path``. These values are
758 typically the result of an object graph traversal. ``root`` is the
759 physical root object, ``context`` will be a model object,
760 ``view_name`` will be the view name used (a Unicode name),
761 ``subpath`` will be a sequence of Unicode names that followed the
762 view name but were not traversed, ``traversed`` will be a sequence of
763 Unicode names that were traversed (including the virtual root path,
764 if any) ``virtual_root`` will be a model object representing the
765 virtual root (or the physical root if traversal was not performed),
766 and ``virtual_root_path`` will be a sequence representing the virtual
767 root path (a sequence of Unicode names) or ``None`` if traversal was
768 not performed.
770 Extra keys for special purpose functionality can be returned as
771 necessary.
773 All values returned in the dictionary will be made available
774 as attributes of the ``request`` object by the :term:`router`.
775 """
778ITraverserFactory = ITraverser # b / c for 1.0 code
781class IViewPermission(Interface):
782 def __call__(context, request):
783 """ Return True if the permission allows, return False if it denies.
784 """
787class IRouter(Interface):
788 """
789 WSGI application which routes requests to 'view' code based on
790 a view registry.
792 """
794 registry = Attribute(
795 """Component architecture registry local to this application."""
796 )
798 def request_context(environ):
799 """
800 Create a new request context from a WSGI environ.
802 The request context is used to push/pop the threadlocals required
803 when processing the request. It also contains an initialized
804 :class:`pyramid.interfaces.IRequest` instance using the registered
805 :class:`pyramid.interfaces.IRequestFactory`. The context may be
806 used as a context manager to control the threadlocal lifecycle:
808 .. code-block:: python
810 with router.request_context(environ) as request:
811 ...
813 Alternatively, the context may be used without the ``with`` statement
814 by manually invoking its ``begin()`` and ``end()`` methods.
816 .. code-block:: python
818 ctx = router.request_context(environ)
819 request = ctx.begin()
820 try:
821 ...
822 finally:
823 ctx.end()
825 """
827 def invoke_request(request):
828 """
829 Invoke the :app:`Pyramid` request pipeline.
831 See :ref:`router_chapter` for information on the request pipeline.
833 The output should be a :class:`pyramid.interfaces.IResponse` object
834 or a raised exception.
836 """
839class IExecutionPolicy(Interface):
840 def __call__(environ, router):
841 """
842 This callable triggers the router to process a raw WSGI environ dict
843 into a response and controls the :app:`Pyramid` request pipeline.
845 The ``environ`` is the raw WSGI environ.
847 The ``router`` is an :class:`pyramid.interfaces.IRouter` object which
848 should be used to create a request object and send it into the
849 processing pipeline.
851 The return value should be a :class:`pyramid.interfaces.IResponse`
852 object or an exception that will be handled by WSGI middleware.
854 The default execution policy simply creates a request and sends it
855 through the pipeline, attempting to render any exception that escapes:
857 .. code-block:: python
859 def simple_execution_policy(environ, router):
860 with router.request_context(environ) as request:
861 try:
862 return router.invoke_request(request)
863 except Exception:
864 return request.invoke_exception_view(reraise=True)
865 """
868class ISettings(IDict):
869 """ Runtime settings utility for pyramid; represents the
870 deployment settings for the application. Implements a mapping
871 interface."""
874# this interface, even if it becomes unused within Pyramid, is
875# imported by other packages (such as traversalwrapper)
876class ILocation(Interface):
877 """Objects that have a structural location"""
879 __parent__ = Attribute("The parent in the location hierarchy")
880 __name__ = Attribute("The name within the parent")
883class IDebugLogger(Interface):
884 """ Interface representing a PEP 282 logger """
887ILogger = IDebugLogger # b/c
890class IRoutePregenerator(Interface):
891 def __call__(request, elements, kw):
893 """ A pregenerator is a function associated by a developer with a
894 :term:`route`. The pregenerator for a route is called by
895 :meth:`pyramid.request.Request.route_url` in order to adjust the set
896 of arguments passed to it by the user for special purposes, such as
897 Pylons 'subdomain' support. It will influence the URL returned by
898 ``route_url``.
900 A pregenerator should return a two-tuple of ``(elements, kw)``
901 after examining the originals passed to this function, which
902 are the arguments ``(request, elements, kw)``. The simplest
903 pregenerator is::
905 def pregenerator(request, elements, kw):
906 return elements, kw
908 You can employ a pregenerator by passing a ``pregenerator``
909 argument to the
910 :meth:`pyramid.config.Configurator.add_route`
911 function.
913 """
916class IRoute(Interface):
917 """ Interface representing the type of object returned from
918 ``IRoutesMapper.get_route``"""
920 name = Attribute('The route name')
921 pattern = Attribute('The route pattern')
922 factory = Attribute(
923 'The :term:`root factory` used by the :app:`Pyramid` router '
924 'when this route matches (or ``None``)'
925 )
926 predicates = Attribute(
927 'A sequence of :term:`route predicate` objects used to '
928 'determine if a request matches this route or not after '
929 'basic pattern matching has been completed.'
930 )
931 pregenerator = Attribute(
932 'This attribute should either be ``None`` or '
933 'a callable object implementing the '
934 '``IRoutePregenerator`` interface'
935 )
937 def match(path):
938 """
939 If the ``path`` passed to this function can be matched by the
940 ``pattern`` of this route, return a dictionary (the
941 'matchdict'), which will contain keys representing the dynamic
942 segment markers in the pattern mapped to values extracted from
943 the provided ``path``.
945 If the ``path`` passed to this function cannot be matched by
946 the ``pattern`` of this route, return ``None``.
947 """
949 def generate(kw):
950 """
951 Generate a URL based on filling in the dynamic segment markers
952 in the pattern using the ``kw`` dictionary provided.
953 """
956class IRoutesMapper(Interface):
957 """ Interface representing a Routes ``Mapper`` object """
959 def get_routes():
960 """ Return a sequence of Route objects registered in the mapper.
961 Static routes will not be returned in this sequence."""
963 def has_routes():
964 """ Returns ``True`` if any route has been registered. """
966 def get_route(name):
967 """ Returns an ``IRoute`` object if a route with the name ``name``
968 was registered, otherwise return ``None``."""
970 def connect(
971 name,
972 pattern,
973 factory=None,
974 predicates=(),
975 pregenerator=None,
976 static=True,
977 ):
978 """ Add a new route. """
980 def generate(name, kw):
981 """ Generate a URL using the route named ``name`` with the
982 keywords implied by kw"""
984 def __call__(request):
985 """ Return a dictionary containing matching information for
986 the request; the ``route`` key of this dictionary will either
987 be a Route object or ``None`` if no route matched; the
988 ``match`` key will be the matchdict or ``None`` if no route
989 matched. Static routes will not be considered for matching. """
992class IResourceURL(Interface):
993 virtual_path = Attribute(
994 'The virtual url path of the resource as a string.'
995 )
996 physical_path = Attribute(
997 'The physical url path of the resource as a string.'
998 )
999 virtual_path_tuple = Attribute(
1000 'The virtual url path of the resource as a tuple. (New in 1.5)'
1001 )
1002 physical_path_tuple = Attribute(
1003 'The physical url path of the resource as a tuple. (New in 1.5)'
1004 )
1007class IPEP302Loader(Interface):
1008 """ See http://www.python.org/dev/peps/pep-0302/#id30.
1009 """
1011 def get_data(path):
1012 """ Retrieve data for and arbitrary "files" from storage backend.
1014 Raise IOError for not found.
1016 Data is returned as bytes.
1017 """
1019 def is_package(fullname):
1020 """ Return True if the module specified by 'fullname' is a package.
1021 """
1023 def get_code(fullname):
1024 """ Return the code object for the module identified by 'fullname'.
1026 Return 'None' if it's a built-in or extension module.
1028 If the loader doesn't have the code object but it does have the source
1029 code, return the compiled source code.
1031 Raise ImportError if the module can't be found by the importer at all.
1032 """
1034 def get_source(fullname):
1035 """ Return the source code for the module identified by 'fullname'.
1037 Return a string, using newline characters for line endings, or None
1038 if the source is not available.
1040 Raise ImportError if the module can't be found by the importer at all.
1041 """
1043 def get_filename(fullname):
1044 """ Return the value of '__file__' if the named module was loaded.
1046 If the module is not found, raise ImportError.
1047 """
1050class IPackageOverrides(IPEP302Loader):
1051 """ Utility for pkg_resources overrides """
1054# VH_ROOT_KEY is an interface; its imported from other packages (e.g.
1055# traversalwrapper)
1056VH_ROOT_KEY = 'HTTP_X_VHM_ROOT'
1059class ILocalizer(Interface):
1060 """ Localizer for a specific language """
1063class ILocaleNegotiator(Interface):
1064 def __call__(request):
1065 """ Return a locale name """
1068class ITranslationDirectories(Interface):
1069 """ A list object representing all known translation directories
1070 for an application"""
1073class IDefaultPermission(Interface):
1074 """ A string object representing the default permission to be used
1075 for all view configurations which do not explicitly declare their
1076 own."""
1079class IDefaultCSRFOptions(Interface):
1080 """ An object representing the default CSRF settings to be used for
1081 all view configurations which do not explicitly declare their own."""
1083 require_csrf = Attribute(
1084 'Boolean attribute. If ``True``, then CSRF checks will be enabled by '
1085 'default for the view unless overridden.'
1086 )
1087 token = Attribute('The key to be matched in the body of the request.')
1088 header = Attribute('The header to be matched with the CSRF token.')
1089 safe_methods = Attribute('A set of safe methods that skip CSRF checks.')
1090 callback = Attribute('A callback to disable CSRF checks per-request.')
1093class ISessionFactory(Interface):
1094 """ An interface representing a factory which accepts a request object and
1095 returns an ISession object """
1097 def __call__(request):
1098 """ Return an ISession object """
1101class ISession(IDict):
1102 """ An interface representing a session (a web session object,
1103 usually accessed via ``request.session``.
1105 Keys and values of a session must be pickleable.
1107 .. warning::
1109 In :app:`Pyramid` 2.0 the session will only be required to support
1110 types that can be serialized using JSON. It's recommended to switch any
1111 session implementations to support only JSON and to only store primitive
1112 types in sessions. See :ref:`pickle_session_deprecation` for more
1113 information about why this change is being made.
1115 .. versionchanged:: 1.9
1117 Sessions are no longer required to implement ``get_csrf_token`` and
1118 ``new_csrf_token``. CSRF token support was moved to the pluggable
1119 :class:`pyramid.interfaces.ICSRFStoragePolicy` configuration hook.
1121 """
1123 # attributes
1125 created = Attribute('Integer representing Epoch time when created.')
1126 new = Attribute('Boolean attribute. If ``True``, the session is new.')
1128 # special methods
1130 def invalidate():
1131 """ Invalidate the session. The action caused by
1132 ``invalidate`` is implementation-dependent, but it should have
1133 the effect of completely dissociating any data stored in the
1134 session with the current request. It might set response
1135 values (such as one which clears a cookie), or it might not.
1137 An invalidated session may be used after the call to ``invalidate``
1138 with the effect that a new session is created to store the data. This
1139 enables workflows requiring an entirely new session, such as in the
1140 case of changing privilege levels or preventing fixation attacks.
1141 """
1143 def changed():
1144 """ Mark the session as changed. A user of a session should
1145 call this method after he or she mutates a mutable object that
1146 is *a value of the session* (it should not be required after
1147 mutating the session itself). For example, if the user has
1148 stored a dictionary in the session under the key ``foo``, and
1149 he or she does ``session['foo'] = {}``, ``changed()`` needn't
1150 be called. However, if subsequently he or she does
1151 ``session['foo']['a'] = 1``, ``changed()`` must be called for
1152 the sessioning machinery to notice the mutation of the
1153 internal dictionary."""
1155 def flash(msg, queue='', allow_duplicate=True):
1156 """ Push a flash message onto the end of the flash queue represented
1157 by ``queue``. An alternate flash message queue can used by passing
1158 an optional ``queue``, which must be a string. If
1159 ``allow_duplicate`` is false, if the ``msg`` already exists in the
1160 queue, it will not be re-added."""
1162 def pop_flash(queue=''):
1163 """ Pop a queue from the flash storage. The queue is removed from
1164 flash storage after this message is called. The queue is returned;
1165 it is a list of flash messages added by
1166 :meth:`pyramid.interfaces.ISession.flash`"""
1168 def peek_flash(queue=''):
1169 """ Peek at a queue in the flash storage. The queue remains in
1170 flash storage after this message is called. The queue is returned;
1171 it is a list of flash messages added by
1172 :meth:`pyramid.interfaces.ISession.flash`
1173 """
1176class ICSRFStoragePolicy(Interface):
1177 """ An object that offers the ability to verify CSRF tokens and generate
1178 new ones."""
1180 def new_csrf_token(request):
1181 """ Create and return a new, random cross-site request forgery
1182 protection token. The token will be an ascii-compatible unicode
1183 string.
1185 """
1187 def get_csrf_token(request):
1188 """ Return a cross-site request forgery protection token. It
1189 will be an ascii-compatible unicode string. If a token was previously
1190 set for this user via ``new_csrf_token``, that token will be returned.
1191 If no CSRF token was previously set, ``new_csrf_token`` will be
1192 called, which will create and set a token, and this token will be
1193 returned.
1195 """
1197 def check_csrf_token(request, token):
1198 """ Determine if the supplied ``token`` is valid. Most implementations
1199 should simply compare the ``token`` to the current value of
1200 ``get_csrf_token`` but it is possible to verify the token using
1201 any mechanism necessary using this method.
1203 Returns ``True`` if the ``token`` is valid, otherwise ``False``.
1205 """
1208class IIntrospector(Interface):
1209 def get(category_name, discriminator, default=None):
1210 """ Get the IIntrospectable related to the category_name and the
1211 discriminator (or discriminator hash) ``discriminator``. If it does
1212 not exist in the introspector, return the value of ``default`` """
1214 def get_category(category_name, default=None, sort_key=None):
1215 """ Get a sequence of dictionaries in the form
1216 ``[{'introspectable':IIntrospectable, 'related':[sequence of related
1217 IIntrospectables]}, ...]`` where each introspectable is part of the
1218 category associated with ``category_name`` .
1220 If the category named ``category_name`` does not exist in the
1221 introspector the value passed as ``default`` will be returned.
1223 If ``sort_key`` is ``None``, the sequence will be returned in the
1224 order the introspectables were added to the introspector. Otherwise,
1225 sort_key should be a function that accepts an IIntrospectable and
1226 returns a value from it (ala the ``key`` function of Python's
1227 ``sorted`` callable)."""
1229 def categories():
1230 """ Return a sorted sequence of category names known by
1231 this introspector """
1233 def categorized(sort_key=None):
1234 """ Get a sequence of tuples in the form ``[(category_name,
1235 [{'introspectable':IIntrospectable, 'related':[sequence of related
1236 IIntrospectables]}, ...])]`` representing all known
1237 introspectables. If ``sort_key`` is ``None``, each introspectables
1238 sequence will be returned in the order the introspectables were added
1239 to the introspector. Otherwise, sort_key should be a function that
1240 accepts an IIntrospectable and returns a value from it (ala the
1241 ``key`` function of Python's ``sorted`` callable)."""
1243 def remove(category_name, discriminator):
1244 """ Remove the IIntrospectable related to ``category_name`` and
1245 ``discriminator`` from the introspector, and fix up any relations
1246 that the introspectable participates in. This method will not raise
1247 an error if an introspectable related to the category name and
1248 discriminator does not exist."""
1250 def related(intr):
1251 """ Return a sequence of IIntrospectables related to the
1252 IIntrospectable ``intr``. Return the empty sequence if no relations
1253 for exist."""
1255 def add(intr):
1256 """ Add the IIntrospectable ``intr`` (use instead of
1257 :meth:`pyramid.interfaces.IIntrospector.add` when you have a custom
1258 IIntrospectable). Replaces any existing introspectable registered
1259 using the same category/discriminator.
1261 This method is not typically called directly, instead it's called
1262 indirectly by :meth:`pyramid.interfaces.IIntrospector.register`"""
1264 def relate(*pairs):
1265 """ Given any number of ``(category_name, discriminator)`` pairs
1266 passed as positional arguments, relate the associated introspectables
1267 to each other. The introspectable related to each pair must have
1268 already been added via ``.add`` or ``.add_intr``; a :exc:`KeyError`
1269 will result if this is not true. An error will not be raised if any
1270 pair has already been associated with another.
1272 This method is not typically called directly, instead it's called
1273 indirectly by :meth:`pyramid.interfaces.IIntrospector.register`
1274 """
1276 def unrelate(*pairs):
1277 """ Given any number of ``(category_name, discriminator)`` pairs
1278 passed as positional arguments, unrelate the associated introspectables
1279 from each other. The introspectable related to each pair must have
1280 already been added via ``.add`` or ``.add_intr``; a :exc:`KeyError`
1281 will result if this is not true. An error will not be raised if any
1282 pair is not already related to another.
1284 This method is not typically called directly, instead it's called
1285 indirectly by :meth:`pyramid.interfaces.IIntrospector.register`
1286 """
1289class IIntrospectable(Interface):
1290 """ An introspectable object used for configuration introspection. In
1291 addition to the methods below, objects which implement this interface
1292 must also implement all the methods of Python's
1293 ``collections.MutableMapping`` (the "dictionary interface"), and must be
1294 hashable."""
1296 title = Attribute('Text title describing this introspectable')
1297 type_name = Attribute('Text type name describing this introspectable')
1298 order = Attribute(
1299 'integer order in which registered with introspector '
1300 '(managed by introspector, usually)'
1301 )
1302 category_name = Attribute('introspection category name')
1303 discriminator = Attribute(
1304 'introspectable discriminator (within category) ' '(must be hashable)'
1305 )
1306 discriminator_hash = Attribute('an integer hash of the discriminator')
1307 action_info = Attribute(
1308 'An IActionInfo object representing the caller '
1309 'that invoked the creation of this introspectable '
1310 '(usually a sentinel until updated during '
1311 'self.register)'
1312 )
1314 def relate(category_name, discriminator):
1315 """ Indicate an intent to relate this IIntrospectable with another
1316 IIntrospectable (the one associated with the ``category_name`` and
1317 ``discriminator``) during action execution.
1318 """
1320 def unrelate(category_name, discriminator):
1321 """ Indicate an intent to break the relationship between this
1322 IIntrospectable with another IIntrospectable (the one associated with
1323 the ``category_name`` and ``discriminator``) during action execution.
1324 """
1326 def register(introspector, action_info):
1327 """ Register this IIntrospectable with an introspector. This method
1328 is invoked during action execution. Adds the introspectable and its
1329 relations to the introspector. ``introspector`` should be an object
1330 implementing IIntrospector. ``action_info`` should be a object
1331 implementing the interface :class:`pyramid.interfaces.IActionInfo`
1332 representing the call that registered this introspectable.
1333 Pseudocode for an implementation of this method:
1335 .. code-block:: python
1337 def register(self, introspector, action_info):
1338 self.action_info = action_info
1339 introspector.add(self)
1340 for methodname, category_name, discriminator in self._relations:
1341 method = getattr(introspector, methodname)
1342 method((i.category_name, i.discriminator),
1343 (category_name, discriminator))
1344 """ # noqa: E501
1346 def __hash__():
1348 """ Introspectables must be hashable. The typical implementation of
1349 an introsepectable's __hash__ is::
1351 return hash((self.category_name,) + (self.discriminator,))
1352 """
1355class IActionInfo(Interface):
1356 """ Class which provides code introspection capability associated with an
1357 action. The ParserInfo class used by ZCML implements the same interface.
1358 """
1360 file = Attribute('Filename of action-invoking code as a string')
1361 line = Attribute(
1362 'Starting line number in file (as an integer) of action-invoking code.'
1363 'This will be ``None`` if the value could not be determined.'
1364 )
1366 def __str__():
1367 """ Return a representation of the action information (including
1368 source code from file, if possible) """
1371class IAssetDescriptor(Interface):
1372 """
1373 Describes an :term:`asset`.
1374 """
1376 def absspec():
1377 """
1378 Returns the absolute asset specification for this asset
1379 (e.g. ``mypackage:templates/foo.pt``).
1380 """
1382 def abspath():
1383 """
1384 Returns an absolute path in the filesystem to the asset.
1385 """
1387 def stream():
1388 """
1389 Returns an input stream for reading asset contents. Raises an
1390 exception if the asset is a directory or does not exist.
1391 """
1393 def isdir():
1394 """
1395 Returns True if the asset is a directory, otherwise returns False.
1396 """
1398 def listdir():
1399 """
1400 Returns iterable of filenames of directory contents. Raises an
1401 exception if asset is not a directory.
1402 """
1404 def exists():
1405 """
1406 Returns True if asset exists, otherwise returns False.
1407 """
1410class IJSONAdapter(Interface):
1411 """
1412 Marker interface for objects that can convert an arbitrary object
1413 into a JSON-serializable primitive.
1414 """
1417class IPredicateList(Interface):
1418 """ Interface representing a predicate list """
1421class IViewDeriver(Interface):
1422 options = Attribute(
1423 'A list of supported options to be passed to '
1424 ':meth:`pyramid.config.Configurator.add_view`. '
1425 'This attribute is optional.'
1426 )
1428 def __call__(view, info):
1429 """
1430 Derive a new view from the supplied view.
1432 View options, package information and registry are available on
1433 ``info``, an instance of :class:`pyramid.interfaces.IViewDeriverInfo`.
1435 The ``view`` is a callable accepting ``(context, request)``.
1437 """
1440class IViewDeriverInfo(Interface):
1441 """ An object implementing this interface is passed to every
1442 :term:`view deriver` during configuration."""
1444 registry = Attribute(
1445 'The "current" application registry where the ' 'view was created'
1446 )
1447 package = Attribute(
1448 'The "current package" where the view '
1449 'configuration statement was found'
1450 )
1451 settings = Attribute(
1452 'The deployment settings dictionary related '
1453 'to the current application'
1454 )
1455 options = Attribute(
1456 'The view options passed to the view, including any '
1457 'default values that were not overriden'
1458 )
1459 predicates = Attribute('The list of predicates active on the view')
1460 original_view = Attribute('The original view object being wrapped')
1461 exception_only = Attribute('The view will only be invoked for exceptions')
1464class IViewDerivers(Interface):
1465 """ Interface for view derivers list """
1468class ICacheBuster(Interface):
1469 """
1470 A cache buster modifies the URL generation machinery for
1471 :meth:`~pyramid.request.Request.static_url`. See :ref:`cache_busting`.
1473 .. versionadded:: 1.6
1474 """
1476 def __call__(request, subpath, kw):
1477 """
1478 Modifies a subpath and/or keyword arguments from which a static asset
1479 URL will be computed during URL generation.
1481 The ``subpath`` argument is a path of ``/``-delimited segments that
1482 represent the portion of the asset URL which is used to find the asset.
1483 The ``kw`` argument is a dict of keywords that are to be passed
1484 eventually to :meth:`~pyramid.request.Request.static_url` for URL
1485 generation. The return value should be a two-tuple of
1486 ``(subpath, kw)`` where ``subpath`` is the relative URL from where the
1487 file is served and ``kw`` is the same input argument. The return value
1488 should be modified to include the cache bust token in the generated
1489 URL.
1491 The ``kw`` dictionary contains extra arguments passed to
1492 :meth:`~pyramid.request.Request.static_url` as well as some extra
1493 items that may be usful including:
1495 - ``pathspec`` is the path specification for the resource
1496 to be cache busted.
1498 - ``rawspec`` is the original location of the file, ignoring
1499 any calls to :meth:`pyramid.config.Configurator.override_asset`.
1501 The ``pathspec`` and ``rawspec`` values are only different in cases
1502 where an asset has been mounted into a virtual location using
1503 :meth:`pyramid.config.Configurator.override_asset`. For example, with
1504 a call to ``request.static_url('myapp:static/foo.png'), the
1505 ``pathspec`` is ``myapp:static/foo.png`` whereas the ``rawspec`` may
1506 be ``themepkg:bar.png``, assuming a call to
1507 ``config.override_asset('myapp:static/foo.png', 'themepkg:bar.png')``.
1508 """
1511# configuration phases: a lower phase number means the actions associated
1512# with this phase will be executed earlier than those with later phase
1513# numbers. The default phase number is 0, FTR.
1515PHASE0_CONFIG = -30
1516PHASE1_CONFIG = -20
1517PHASE2_CONFIG = -10
1518PHASE3_CONFIG = 0