Michael Merickel
2018-10-26 4149922e64aecf2a213f8efb120cd2d61fed3eb7
commit | author | age
c151ad 1 from zope.deprecation import deprecated
MM 2
0c29cf 3 from zope.interface import Attribute, Interface
eca67a 4
bc37a5 5 from pyramid.compat import PY2
475532 6
4aa22c 7 # public API interfaces
0c29cf 8
4aa22c 9
8f45be 10 class IContextFound(Interface):
fd5ae9 11     """ An event type that is emitted after :app:`Pyramid` finds a
8f45be 12     :term:`context` object but before it calls any view code.  See the
c81aad 13     documentation attached to :class:`pyramid.events.ContextFound`
8f45be 14     for more information.
CM 15
012b97 16     .. note::
M 17
18        For backwards compatibility with versions of
fd5ae9 19        :app:`Pyramid` before 1.0, this event interface can also be
c81aad 20        imported as :class:`pyramid.interfaces.IAfterTraversal`.
8f45be 21     """
0c29cf 22
4aa22c 23     request = Attribute('The request object')
8f45be 24
0c29cf 25
8f45be 26 IAfterTraversal = IContextFound
0c29cf 27
4aa22c 28
d4f5a8 29 class IBeforeTraversal(Interface):
499b78 30     """
4112d6 31     An event type that is emitted after :app:`Pyramid` attempted to find a
BJR 32     route but before it calls any traversal or view code. See the documentation
499b78 33     attached to :class:`pyramid.events.Routefound` for more information.
DS 34     """
0c29cf 35
499b78 36     request = Attribute('The request object')
0c29cf 37
499b78 38
4aa22c 39 class INewRequest(Interface):
fd5ae9 40     """ An event type that is emitted whenever :app:`Pyramid`
8f45be 41     begins to process a new request.  See the documentation attached
c81aad 42     to :class:`pyramid.events.NewRequest` for more information."""
0c29cf 43
4aa22c 44     request = Attribute('The request object')
0c29cf 45
012b97 46
4aa22c 47 class INewResponse(Interface):
fd5ae9 48     """ An event type that is emitted whenever any :app:`Pyramid`
8f45be 49     view returns a response. See the
c81aad 50     documentation attached to :class:`pyramid.events.NewResponse`
8f45be 51     for more information."""
0c29cf 52
eb7ea4 53     request = Attribute('The request object')
4aa22c 54     response = Attribute('The response object')
0c29cf 55
4aa22c 56
8f45be 57 class IApplicationCreated(Interface):
c6895b 58     """ Event issued when the
aff443 59     :meth:`pyramid.config.Configurator.make_wsgi_app` method
8f45be 60     is called.  See the documentation attached to
c81aad 61     :class:`pyramid.events.ApplicationCreated` for more
8f45be 62     information.
CM 63
012b97 64     .. note::
M 65
66        For backwards compatibility with :app:`Pyramid`
c81aad 67        versions before 1.0, this interface can also be imported as
CM 68        :class:`pyramid.interfaces.IWSGIApplicationCreatedEvent`.
8f45be 69     """
0c29cf 70
e6c2d2 71     app = Attribute("Created application")
239a93 72
0c29cf 73
MM 74 IWSGIApplicationCreatedEvent = IApplicationCreated  # b /c
75
4aa22c 76
99edc5 77 class IResponse(Interface):
55241c 78     """ Represents a WSGI response using the WebOb response interface.
TL 79     Some attribute and method documentation of this interface references
80     :rfc:`2616`.
51fb07 81
CM 82     This interface is most famously implemented by
83     :class:`pyramid.response.Response` and the HTTP exception classes in
84     :mod:`pyramid.httpexceptions`."""
85
86     RequestClass = Attribute(
0c29cf 87         """ Alias for :class:`pyramid.request.Request` """
MM 88     )
99edc5 89
CM 90     def __call__(environ, start_response):
51fb07 91         """ :term:`WSGI` call interface, should call the start_response
CM 92         callback and should return an iterable"""
93
94     accept_ranges = Attribute(
95         """Gets and sets and deletes the Accept-Ranges header. For more
0c29cf 96         information on Accept-Ranges see RFC 2616, section 14.5"""
MM 97     )
51fb07 98
CM 99     age = Attribute(
100         """Gets and sets and deletes the Age header. Converts using int.
0c29cf 101         For more information on Age see RFC 2616, section 14.6."""
MM 102     )
51fb07 103
CM 104     allow = Attribute(
105         """Gets and sets and deletes the Allow header. Converts using
0c29cf 106         list. For more information on Allow see RFC 2616, Section 14.7."""
MM 107     )
51fb07 108
CM 109     app_iter = Attribute(
110         """Returns the app_iter of the response.
111
112         If body was set, this will create an app_iter from that body
0c29cf 113         (a single-item list)"""
MM 114     )
51fb07 115
CM 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. """
119
120     body = Attribute(
121         """The body of the response, as a str. This will read in the entire
0c29cf 122         app_iter if necessary."""
MM 123     )
51fb07 124
CM 125     body_file = Attribute(
126         """A file-like object that can be used to write to the body. If you
0c29cf 127         passed in a list app_iter, that app_iter will be modified by writes."""
MM 128     )
51fb07 129
CM 130     cache_control = Attribute(
0c29cf 131         """Get/set/modify the Cache-Control header (RFC 2616 section 14.9)"""
MM 132     )
51fb07 133
CM 134     cache_expires = Attribute(
135         """ Get/set the Cache-Control and Expires headers. This sets the
0c29cf 136             response to expire in the number of seconds passed when set. """
MM 137     )
51fb07 138
0c29cf 139     charset = Attribute("""Get/set the charset (in the Content-Type)""")
51fb07 140
CM 141     def conditional_response_app(environ, start_response):
142         """ Like the normal __call__ interface, but checks conditional
143         headers:
144
145         - If-Modified-Since (304 Not Modified; only on GET, HEAD)
146
147         - If-None-Match (304 Not Modified; only on GET, HEAD)
148
149         - Range (406 Partial Content; only on GET, HEAD)"""
150
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
0c29cf 154         19.5.1."""
MM 155     )
51fb07 156
CM 157     content_encoding = Attribute(
158         """Gets and sets and deletes the Content-Encoding header.  For more
0c29cf 159         information about Content-Encoding see RFC 2616 section 14.11."""
MM 160     )
51fb07 161
CM 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
0c29cf 165         section 14.12."""
MM 166     )
51fb07 167
CM 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.
0c29cf 171         Converts using int. """
MM 172     )
51fb07 173
CM 174     content_location = Attribute(
175         """Gets and sets and deletes the Content-Location header. For more
0c29cf 176         information on Content-Location see RFC 2616 section 14.14."""
MM 177     )
51fb07 178
CM 179     content_md5 = Attribute(
180         """Gets and sets and deletes the Content-MD5 header. For more
0c29cf 181         information on Content-MD5 see RFC 2616 section 14.14."""
MM 182     )
51fb07 183
25c64c 184     content_range = Attribute(
51fb07 185         """Gets and sets and deletes the Content-Range header. For more
CM 186         information on Content-Range see section 14.16. Converts using
0c29cf 187         ContentRange object."""
MM 188     )
51fb07 189
CM 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;
0c29cf 194         otherwise they will be preserved."""
MM 195     )
51fb07 196
CM 197     content_type_params = Attribute(
012b97 198         """A dictionary of all the parameters in the content type.  This is
51fb07 199         not a view, set to change, modifications of the dict would not
0c29cf 200         be applied otherwise."""
MM 201     )
51fb07 202
CM 203     def copy():
204         """ Makes a copy of the response and returns the copy. """
205
206     date = Attribute(
207         """Gets and sets and deletes the Date header. For more information on
0c29cf 208         Date see RFC 2616 section 14.18. Converts using HTTP date."""
MM 209     )
51fb07 210
073fac 211     def delete_cookie(name, path='/', domain=None):
51fb07 212         """ Delete a cookie from the client. Note that path and domain must
CM 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. """
215
216     def encode_content(encoding='gzip', lazy=False):
217         """ Encode the content with the given encoding (only gzip and
218         identity are supported)."""
219
220     environ = Attribute(
221         """Get/set the request environ associated with this response,
0c29cf 222         if any."""
MM 223     )
51fb07 224
CM 225     etag = Attribute(
226         """ Gets and sets and deletes the ETag header. For more information
0c29cf 227         on ETag see RFC 2616 section 14.19. Converts using Entity tag."""
MM 228     )
51fb07 229
CM 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
0c29cf 233         HTTP date."""
MM 234     )
51fb07 235
0c29cf 236     headerlist = Attribute(""" The list of response headers. """)
51fb07 237
0c29cf 238     headers = Attribute(""" The headers in a dictionary-like object """)
51fb07 239
CM 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
0c29cf 243         using HTTP date."""
MM 244     )
51fb07 245
CM 246     location = Attribute(
247         """ Gets and sets and deletes the Location header. For more
0c29cf 248         information on Location see RFC 2616 section 14.30."""
MM 249     )
51fb07 250
CM 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 """
255
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. """
261
262     pragma = Attribute(
263         """ Gets and sets and deletes the Pragma header. For more information
0c29cf 264         on Pragma see RFC 2616 section 14.32. """
MM 265     )
51fb07 266
CM 267     request = Attribute(
0c29cf 268         """ Return the request associated with this response if any. """
MM 269     )
51fb07 270
CM 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
0c29cf 274         using HTTP date or delta seconds."""
MM 275     )
51fb07 276
CM 277     server = Attribute(
278         """ Gets and sets and deletes the Server header. For more information
0c29cf 279         on Server see RFC216 section 14.38. """
MM 280     )
51fb07 281
0c29cf 282     def set_cookie(
MM 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     ):
51fb07 294         """ Set (add) a cookie for the response """
CM 295
0c29cf 296     status = Attribute(""" The status string. """)
51fb07 297
0c29cf 298     status_int = Attribute(""" The status as an integer """)
51fb07 299
CM 300     unicode_body = Attribute(
301         """ Get/set the unicode value of the body (using the charset of
0c29cf 302         the Content-Type)"""
MM 303     )
51fb07 304
41662f 305     def unset_cookie(name, strict=True):
51fb07 306         """ Unset a cookie with the given name (remove it from the
CM 307         response)."""
308
309     vary = Attribute(
310         """Gets and sets and deletes the Vary header. For more information
0c29cf 311         on Vary see section 14.44. Converts using list."""
MM 312     )
51fb07 313
CM 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
0c29cf 317         using 'parse_auth' and 'serialize_auth'. """
MM 318     )
d96ff9 319
0c29cf 320
MM 321 class IException(Interface):  # not an API
d96ff9 322     """ An interface representing a generic exception """
0c29cf 323
d96ff9 324
CM 325 class IExceptionResponse(IException, IResponse):
a7e625 326     """ An interface representing a WSGI response which is also an exception
CM 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
99edc5 331     :class:`pyramid.httpexceptions.HTTPNotFound` and
CM 332     :class:`pyramid.httpexceptions.HTTPForbidden`)."""
0c29cf 333
85093d 334     def prepare(environ):
CM 335         """ Prepares the response for being called as a WSGI application """
0c29cf 336
d96ff9 337
5c52da 338 class IDict(Interface):
CM 339     # Documentation-only interface
340
341     def __contains__(k):
342         """ Return ``True`` if key ``k`` exists in the dictionary."""
343
344     def __setitem__(k, value):
345         """ Set a key/value pair into the dictionary"""
012b97 346
5c52da 347     def __delitem__(k):
CM 348         """ Delete an item from the dictionary which is passed to the
349         renderer as the renderer globals dictionary."""
012b97 350
5c52da 351     def __getitem__(k):
CM 352         """ Return the value for key ``k`` from the dictionary or raise a
353         KeyError if the key doesn't exist"""
354
355     def __iter__():
356         """ Return an iterator over the keys of this dictionary """
012b97 357
5c52da 358     def get(k, default=None):
CM 359         """ Return the value for key ``k`` from the renderer dictionary, or
360         the default if no such value exists."""
361
362     def items():
363         """ Return a list of [(k,v)] pairs from the dictionary """
364
365     def keys():
366         """ Return a list of keys from the dictionary """
367
368     def values():
369         """ Return a list of values from the dictionary """
370
bc37a5 371     if PY2:
475532 372
CM 373         def iterkeys():
374             """ Return an iterator of keys from the dictionary """
375
376         def iteritems():
377             """ Return an iterator of (k,v) pairs from the dictionary """
378
379         def itervalues():
380             """ Return an iterator of values from the dictionary """
381
382         has_key = __contains__
5c52da 383
CM 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."""
388
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."""
392
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"""
012b97 399
5c52da 400     def update(d):
CM 401         """ Update the renderer dictionary with another dictionary ``d``."""
402
403     def clear():
404         """ Clear all values from the dictionary """
405
0c29cf 406
5c52da 407 class IBeforeRender(IDict):
a76e99 408     """
7709b1 409     Subscribers to this event may introspect and modify the set of
a76e99 410     :term:`renderer globals` before they are passed to a :term:`renderer`.
5c52da 411     The event object itself provides a dictionary-like interface for adding
CM 412     and removing :term:`renderer globals`.  The keys and values of the
413     dictionary are those globals.  For example::
012b97 414
a76e99 415       from repoze.events import subscriber
CM 416       from pyramid.interfaces import IBeforeRender
417
418       @subscriber(IBeforeRender)
419       def add_global(event):
420           event['mykey'] = 'foo'
421
2033ee 422     .. seealso::
SP 423
424         See also :ref:`beforerender_event`.
a76e99 425     """
0c29cf 426
MM 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     )
432
9a66aa 433
b04ae5 434 class IRendererInfo(Interface):
MM 435     """ An object implementing this interface is passed to every
436     :term:`renderer factory` constructor as its only argument (conventionally
437     named ``info``)"""
0c29cf 438
b04ae5 439     name = Attribute('The value passed by the user as the renderer name')
0c29cf 440     package = Attribute(
MM 441         'The "current package" when the renderer '
442         'configuration statement was found'
443     )
b04ae5 444     type = Attribute('The renderer type name')
0c29cf 445     registry = Attribute(
MM 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     )
b04ae5 452
ec4691 453     def clone():
MM 454         """ Return a shallow copy that does not share any mutable state."""
0c29cf 455
ec4691 456
b04ae5 457 class IRendererFactory(Interface):
MM 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         """
0c29cf 463
b04ae5 464
e26903 465 class IRenderer(Interface):
CM 466     def __call__(value, system):
b04ae5 467         """ Call the renderer with the result of the
e26903 468         view (``value``) passed in and return a result (a string or
CM 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)."""
477
0c29cf 478
e26903 479 class ITemplateRenderer(IRenderer):
CM 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 """
b04ae5 485
0c29cf 486
b04ae5 487 deprecated(
MM 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 '
0c29cf 491     'renderers which have been split into their own packages.',
MM 492 )
493
e26903 494
8739f5 495 class IViewMapper(Interface):
CM 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`."""
0c29cf 502
8739f5 503
CM 504 class 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         """
0c29cf 516
8739f5 517
a9fb52 518 class IAuthenticationPolicy(Interface):
c81aad 519     """ An object representing a Pyramid authentication policy. """
fe83c6 520
4aa22c 521     def authenticated_userid(request):
fe83c6 522         """ Return the authenticated :term:`userid` or ``None`` if
MM 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``.
529
530         """
2526d8 531
CM 532     def unauthenticated_userid(request):
fe83c6 533         """ Return the *unauthenticated* userid.  This method
MM 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.
539
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.
544
545         """
4aa22c 546
CM 547     def effective_principals(request):
548         """ Return a sequence representing the effective principals
fe83c6 549         typically including the :term:`userid` and any groups belonged
MM 550         to by the current user, always including 'system' groups such
551         as ``pyramid.security.Everyone`` and
552         ``pyramid.security.Authenticated``.
553
554         """
4aa22c 555
c7afe4 556     def remember(request, userid, **kw):
4aa22c 557         """ Return a set of headers suitable for 'remembering' the
fe83c6 558         :term:`userid` named ``userid`` when set in a response.  An
MM 559         individual authentication policy and its consumers can
c62f7d 560         decide on the composition and meaning of ``**kw``.
fe83c6 561
MM 562         """
012b97 563
4aa22c 564     def forget(request):
CM 565         """ Return a set of headers suitable for 'forgetting' the
fe83c6 566         current user on subsequent requests.
MM 567
568         """
4aa22c 569
0c29cf 570
4aa22c 571 class IAuthorizationPolicy(Interface):
c81aad 572     """ An object representing a Pyramid authorization policy. """
0c29cf 573
4aa22c 574     def permits(context, principals, permission):
213001 575         """ Return an instance of :class:`pyramid.security.Allowed` if any
MM 576         of the ``principals`` is allowed the ``permission`` in the current
577         ``context``, else return an instance of
578         :class:`pyramid.security.Denied`.
57cc86 579         """
012b97 580
4aa22c 581     def principals_allowed_by_permission(context, permission):
57cc86 582         """ Return a set of principal identifiers allowed by the
CM 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."""
4aa22c 589
0c29cf 590
MM 591 class IMultiDict(IDict):  # docs-only interface
2a1c3f 592     """
CM 593     An ordered dictionary that can have multiple values for each key. A
b9a6b3 594     multidict adds the methods ``getall``, ``getone``, ``mixed``, ``extend``,
2a1c3f 595     ``add``, and ``dict_of_lists`` to the normal dictionary interface.  A
CM 596     multidict data structure is used as ``request.POST``, ``request.GET``,
597     and ``request.params`` within an :app:`Pyramid` application.
598     """
599
600     def add(key, value):
601         """ Add the key and value, not overwriting any previous value. """
602
603     def dict_of_lists():
604         """
605         Returns a dictionary where each key is associated with a list of
606         values.
607         """
608
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."""
614
615     def getall(key):
616         """ Return a list of all values matching the key (may be an empty
617         list) """
618
619     def getone(key):
620         """ Get one value matching the key, raising a KeyError if multiple
621         values were found. """
622
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. """
d2973d 628
0c29cf 629
d2973d 630 # internal interfaces
0c29cf 631
d2973d 632
CM 633 class IRequest(Interface):
634     """ Request type interface attached to all request objects """
0c29cf 635
d2973d 636
b4843b 637 class ITweens(Interface):
af2323 638     """ Marker interface for utility registration representing the ordered
b4843b 639     set of a configuration's tween factories"""
af2323 640
0c29cf 641
af2323 642 class IRequestHandler(Interface):
CM 643     """ """
0c29cf 644
af2323 645     def __call__(self, request):
0d4963 646         """ Must return a tuple of IReqest, IResponse or raise an exception.
CM 647         The ``request`` argument will be an instance of an object that
648         provides IRequest."""
af2323 649
0c29cf 650
MM 651 IRequest.combined = IRequest  # for exception view lookups
652
d2973d 653
d7f34b 654 class IRequestExtensions(Interface):
MM 655     """ Marker interface for storing request extensions (properties and
656     methods) which will be added to the request object."""
0c29cf 657
d7f34b 658     descriptors = Attribute(
0c29cf 659         """A list of descriptors that will be added to each request."""
MM 660     )
661     methods = Attribute("""A list of methods to be added to each request.""")
662
74d503 663
d2973d 664 class IRouteRequest(Interface):
CM 665     """ *internal only* interface used as in a utility lookup to find
666     route-specific interfaces.  Not an API."""
0c29cf 667
d2973d 668
121f45 669 class IAcceptOrder(Interface):
MM 670     """
671     Marker interface for a list of accept headers with the most important
672     first.
673
674     """
675
0c29cf 676
b29429 677 class IStaticURLInfo(Interface):
3e2f12 678     """ A policy for generating URLs to static assets """
0c29cf 679
cda7f6 680     def add(config, name, spec, **extra):
b29429 681         """ Add a new static info registration """
CM 682
683     def generate(path, request, **kw):
684         """ Generate a URL for the given path """
a0b40c 685
6e29b4 686     def add_cache_buster(config, spec, cache_buster):
MM 687         """ Add a new cache buster to a particular set of assets """
688
0c29cf 689
c8cf22 690 class IResponseFactory(Interface):
da5f5f 691     """ A utility which generates a response """
0c29cf 692
da5f5f 693     def __call__(request):
MM 694         """ Return a response object implementing IResponse,
695         e.g. :class:`pyramid.response.Response`). It should handle the
696         case when ``request`` is ``None``."""
7de404 697
0c29cf 698
81a833 699 class IRequestFactory(Interface):
CM 700     """ A utility which generates a request """
0c29cf 701
81a833 702     def __call__(environ):
04cc91 703         """ Return an instance of ``pyramid.request.Request``"""
81a833 704
CM 705     def blank(path):
706         """ Return an empty request object (see
8c6a4c 707         :meth:`pyramid.request.Request.blank`)"""
81a833 708
0c29cf 709
ff1213 710 class IViewClassifier(Interface):
CM 711     """ *Internal only* marker interface for views."""
712
0c29cf 713
ff1213 714 class IExceptionViewClassifier(Interface):
CM 715     """ *Internal only* marker interface for exception views."""
0c29cf 716
ff1213 717
7de404 718 class IView(Interface):
CM 719     def __call__(context, request):
99edc5 720         """ Must return an object that implements IResponse. """
d66bfb 721
0c29cf 722
d66bfb 723 class ISecuredView(IView):
573184 724     """ *Internal only* interface.  Not an API. """
0c29cf 725
d66bfb 726     def __call_permissive__(context, request):
CM 727         """ Guaranteed-permissive version of __call__ """
728
729     def __permitted__(context, request):
730         """ Return True if view execution will be permitted using the
731         context and request, False otherwise"""
732
0c29cf 733
d66bfb 734 class IMultiView(ISecuredView):
CM 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."""
0c29cf 738
ff1213 739     def add(view, predicates, order, accept=None, phash=None):
d66bfb 740         """ Add a view to the multiview. """
0c29cf 741
5ed24b 742
358dc2 743 class IRootFactory(Interface):
8b1f6e 744     def __call__(request):
CM 745         """ Return a root object based on the request """
dfc2b6 746
0c29cf 747
dfc2b6 748 class IDefaultRootFactory(Interface):
8b1f6e 749     def __call__(request):
dfc2b6 750         """ Return the *default* root object for an application """
0c29cf 751
612d74 752
4df575 753 class ITraverser(Interface):
8b1f6e 754     def __call__(request):
80a25e 755         """ Return a dictionary with (at least) the keys ``root``,
CM 756         ``context``, ``view_name``, ``subpath``, ``traversed``,
757         ``virtual_root``, and ``virtual_root_path``.  These values are
f426e5 758         typically the result of an object graph traversal.  ``root`` is the
CM 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.
80a25e 769
f426e5 770         Extra keys for special purpose functionality can be returned as
80a25e 771         necessary.
CM 772
773         All values returned in the dictionary will be made available
f426e5 774         as attributes of the ``request`` object by the :term:`router`.
80a25e 775         """
93a4f5 776
0c29cf 777
MM 778 ITraverserFactory = ITraverser  # b / c for 1.0 code
779
8f8869 780
2466f6 781 class IViewPermission(Interface):
d7e43b 782     def __call__(context, request):
b04ae5 783         """ Return True if the permission allows, return False if it denies.
MM 784         """
0c29cf 785
2466f6 786
eba6f8 787 class IRouter(Interface):
822653 788     """
MM 789     WSGI application which routes requests to 'view' code based on
790     a view registry.
791
792     """
0c29cf 793
9dd823 794     registry = Attribute(
0c29cf 795         """Component architecture registry local to this application."""
MM 796     )
012b97 797
822653 798     def request_context(environ):
0bee84 799         """
822653 800         Create a new request context from a WSGI environ.
0bee84 801
822653 802         The request context is used to push/pop the threadlocals required
MM 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:
807
808         .. code-block:: python
809
810             with router.request_context(environ) as request:
811                 ...
812
813         Alternatively, the context may be used without the ``with`` statement
814         by manually invoking its ``begin()`` and ``end()`` methods.
815
816         .. code-block:: python
817
818             ctx = router.request_context(environ)
819             request = ctx.begin()
820             try:
821                 ...
822             finally:
823                 ctx.end()
824
0bee84 825         """
MM 826
827     def invoke_request(request):
828         """
829         Invoke the :app:`Pyramid` request pipeline.
830
831         See :ref:`router_chapter` for information on the request pipeline.
822653 832
MM 833         The output should be a :class:`pyramid.interfaces.IResponse` object
834         or a raised exception.
835
0bee84 836         """
MM 837
0c29cf 838
0bee84 839 class IExecutionPolicy(Interface):
MM 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.
844
845         The ``environ`` is the raw WSGI environ.
846
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.
850
851         The return value should be a :class:`pyramid.interfaces.IResponse`
852         object or an exception that will be handled by WSGI middleware.
853
2e015c 854         The default execution policy simply creates a request and sends it
822653 855         through the pipeline, attempting to render any exception that escapes:
0bee84 856
MM 857         .. code-block:: python
858
859             def simple_execution_policy(environ, router):
822653 860                 with router.request_context(environ) as request:
MM 861                     try:
862                         return router.invoke_request(request)
863                     except Exception:
864                         return request.invoke_exception_view(reraise=True)
0bee84 865         """
MM 866
0c29cf 867
0bee84 868 class ISettings(IDict):
c81aad 869     """ Runtime settings utility for pyramid; represents the
8b1f6e 870     deployment settings for the application.  Implements a mapping
CM 871     interface."""
012b97 872
0c29cf 873
c81aad 874 # this interface, even if it becomes unused within Pyramid, is
cba2e1 875 # imported by other packages (such as traversalwrapper)
cbdc36 876 class ILocation(Interface):
CM 877     """Objects that have a structural location"""
0c29cf 878
cbdc36 879     __parent__ = Attribute("The parent in the location hierarchy")
CM 880     __name__ = Attribute("The name within the parent")
0c29cf 881
cbdc36 882
bd39b1 883 class IDebugLogger(Interface):
47b4d3 884     """ Interface representing a PEP 282 logger """
62267e 885
0c29cf 886
MM 887 ILogger = IDebugLogger  # b/c
888
bd39b1 889
70f1cd 890 class IRoutePregenerator(Interface):
CM 891     def __call__(request, elements, kw):
fb90f0 892
CM 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``.
70f1cd 899
CM 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::
904
905             def pregenerator(request, elements, kw):
906                 return elements, kw
907
908         You can employ a pregenerator by passing a ``pregenerator``
909         argument to the
aff443 910         :meth:`pyramid.config.Configurator.add_route`
70f1cd 911         function.
CM 912
913         """
914
0c29cf 915
74409d 916 class IRoute(Interface):
CM 917     """ Interface representing the type of object returned from
918     ``IRoutesMapper.get_route``"""
0c29cf 919
74409d 920     name = Attribute('The route name')
CM 921     pattern = Attribute('The route pattern')
922     factory = Attribute(
fd5ae9 923         'The :term:`root factory` used by the :app:`Pyramid` router '
0c29cf 924         'when this route matches (or ``None``)'
MM 925     )
74409d 926     predicates = Attribute(
CM 927         'A sequence of :term:`route predicate` objects used to '
c337a8 928         'determine if a request matches this route or not after '
0c29cf 929         'basic pattern matching has been completed.'
MM 930     )
931     pregenerator = Attribute(
932         'This attribute should either be ``None`` or '
933         'a callable object implementing the '
934         '``IRoutePregenerator`` interface'
935     )
0445bf 936
74409d 937     def match(path):
CM 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``.
944
945         If the ``path`` passed to this function cannot be matched by
946         the ``pattern`` of this route, return ``None``.
947         """
0c29cf 948
74409d 949     def generate(kw):
CM 950         """
951         Generate a URL based on filling in the dynamic segment markers
952         in the pattern using the ``kw`` dictionary provided.
953         """
954
0c29cf 955
62267e 956 class IRoutesMapper(Interface):
CM 957     """ Interface representing a Routes ``Mapper`` object """
0c29cf 958
8b1f6e 959     def get_routes():
e725cf 960         """ Return a sequence of Route objects registered in the mapper.
CM 961         Static routes will not be returned in this sequence."""
8b1f6e 962
74409d 963     def has_routes():
CM 964         """ Returns ``True`` if any route has been registered. """
965
966     def get_route(name):
967         """ Returns an ``IRoute`` object if a route with the name ``name``
968         was registered, otherwise return ``None``."""
969
0c29cf 970     def connect(
MM 971         name,
972         pattern,
973         factory=None,
974         predicates=(),
975         pregenerator=None,
976         static=True,
977     ):
8b1f6e 978         """ Add a new route. """
CM 979
980     def generate(name, kw):
981         """ Generate a URL using the route named ``name`` with the
982         keywords implied by kw"""
983
984     def __call__(request):
74409d 985         """ Return a dictionary containing matching information for
CM 986         the request; the ``route`` key of this dictionary will either
987         be a Route object or ``None`` if no route matched; the
51b2f9 988         ``match`` key will be the matchdict or ``None`` if no route
90ed75 989         matched.  Static routes will not be considered for matching.  """
8b1f6e 990
0c29cf 991
c51896 992 class IResourceURL(Interface):
db0185 993     virtual_path = Attribute(
CM 994         'The virtual url path of the resource as a string.'
0c29cf 995     )
db0185 996     physical_path = Attribute(
CM 997         'The physical url path of the resource as a string.'
0c29cf 998     )
db0185 999     virtual_path_tuple = Attribute(
CM 1000         'The virtual url path of the resource as a tuple.  (New in 1.5)'
0c29cf 1001     )
e744e9 1002     physical_path_tuple = Attribute(
db0185 1003         'The physical url path of the resource as a tuple. (New in 1.5)'
0c29cf 1004     )
MM 1005
c51896 1006
bea48e 1007 class IPEP302Loader(Interface):
TS 1008     """ See http://www.python.org/dev/peps/pep-0302/#id30.
1009     """
0c29cf 1010
bea48e 1011     def get_data(path):
TS 1012         """ Retrieve data for and arbitrary "files" from storage backend.
1013
1014         Raise IOError for not found.
1015
1016         Data is returned as bytes.
1017         """
1018
1019     def is_package(fullname):
1020         """ Return True if the module specified by 'fullname' is a package.
1021         """
1022
1023     def get_code(fullname):
1024         """ Return the code object for the module identified by 'fullname'.
0445bf 1025
bea48e 1026         Return 'None' if it's a built-in or extension module.
0445bf 1027
bea48e 1028         If the loader doesn't have the code object but it does have the source
TS 1029         code, return the compiled source code.
1030
1031         Raise ImportError if the module can't be found by the importer at all.
1032         """
1033
1034     def get_source(fullname):
1035         """ Return the source code for the module identified by 'fullname'.
0445bf 1036
bea48e 1037         Return a string, using newline characters for line endings, or None
TS 1038         if the source is not available.
0445bf 1039
bea48e 1040         Raise ImportError if the module can't be found by the importer at all.
TS 1041         """
1042
1043     def get_filename(fullname):
1044         """ Return the value of '__file__' if the named module was loaded.
0445bf 1045
bea48e 1046         If the module is not found, raise ImportError.
TS 1047         """
1048
1049
1050 class IPackageOverrides(IPEP302Loader):
2869fc 1051     """ Utility for pkg_resources overrides """
CM 1052
0c29cf 1053
a7a6d7 1054 # VH_ROOT_KEY is an interface; its imported from other packages (e.g.
CM 1055 # traversalwrapper)
ff1213 1056 VH_ROOT_KEY = 'HTTP_X_VHM_ROOT'
7534ba 1057
0c29cf 1058
7534ba 1059 class ILocalizer(Interface):
CM 1060     """ Localizer for a specific language """
0c29cf 1061
012b97 1062
7534ba 1063 class ILocaleNegotiator(Interface):
CM 1064     def __call__(request):
1065         """ Return a locale name """
1066
0c29cf 1067
7534ba 1068 class ITranslationDirectories(Interface):
CM 1069     """ A list object representing all known translation directories
1070     for an application"""
0c29cf 1071
d96ff9 1072
e25a70 1073 class IDefaultPermission(Interface):
CM 1074     """ A string object representing the default permission to be used
1075     for all view configurations which do not explicitly declare their
1076     own."""
968209 1077
0c29cf 1078
de3d0c 1079 class IDefaultCSRFOptions(Interface):
MM 1080     """ An object representing the default CSRF settings to be used for
1081     all view configurations which do not explicitly declare their own."""
0c29cf 1082
de3d0c 1083     require_csrf = Attribute(
MM 1084         'Boolean attribute. If ``True``, then CSRF checks will be enabled by '
0c29cf 1085         'default for the view unless overridden.'
MM 1086     )
de3d0c 1087     token = Attribute('The key to be matched in the body of the request.')
MM 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.')
17fa5e 1090     callback = Attribute('A callback to disable CSRF checks per-request.')
de3d0c 1091
0c29cf 1092
968209 1093 class ISessionFactory(Interface):
CM 1094     """ An interface representing a factory which accepts a request object and
1095     returns an ISession object """
0c29cf 1096
968209 1097     def __call__(request):
CM 1098         """ Return an ISession object """
0c29cf 1099
968209 1100
866949 1101 class ISession(IDict):
968209 1102     """ An interface representing a session (a web session object,
CM 1103     usually accessed via ``request.session``.
1104
1105     Keys and values of a session must be pickleable.
682a9b 1106
c31883 1107     .. warning::
MM 1108
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.
1114
682a9b 1115     .. versionchanged:: 1.9
MM 1116
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.
1120
968209 1121     """
CM 1122
1123     # attributes
1124
1125     created = Attribute('Integer representing Epoch time when created.')
1126     new = Attribute('Boolean attribute.  If ``True``, the session is new.')
1127
1128     # special methods
1129
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
dd4f73 1135         values (such as one which clears a cookie), or it might not.
MM 1136
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         """
968209 1142
CM 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."""
1154
6f6d36 1155     def flash(msg, queue='', allow_duplicate=True):
CM 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
bfb395 1160         queue, it will not be re-added."""
4df636 1161
6f6d36 1162     def pop_flash(queue=''):
CM 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
be03f7 1166         :meth:`pyramid.interfaces.ISession.flash`"""
6f6d36 1167
CM 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
be03f7 1172         :meth:`pyramid.interfaces.ISession.flash`
319793 1173         """
CM 1174
1175
fe0d22 1176 class ICSRFStoragePolicy(Interface):
a2c7c7 1177     """ An object that offers the ability to verify CSRF tokens and generate
682a9b 1178     new ones."""
a2c7c7 1179
MW 1180     def new_csrf_token(request):
682a9b 1181         """ Create and return a new, random cross-site request forgery
MM 1182         protection token. The token will be an ascii-compatible unicode
1183         string.
1184
1185         """
a2c7c7 1186
MW 1187     def get_csrf_token(request):
1188         """ Return a cross-site request forgery protection token.  It
682a9b 1189         will be an ascii-compatible unicode string.  If a token was previously
MM 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.
eb2fee 1194
a2c7c7 1195         """
MW 1196
3f14d6 1197     def check_csrf_token(request, token):
MM 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.
1202
1203         Returns ``True`` if the ``token`` is valid, otherwise ``False``.
1204
1205         """
1206
a2c7c7 1207
3b5ccb 1208 class IIntrospector(Interface):
CM 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
8a32e3 1212         not exist in the introspector, return the value of ``default`` """
3b5ccb 1213
79f34b 1214     def get_category(category_name, default=None, sort_key=None):
412b4a 1215         """ Get a sequence of dictionaries in the form
CM 1216         ``[{'introspectable':IIntrospectable, 'related':[sequence of related
1217         IIntrospectables]}, ...]`` where each introspectable is part of the
79f34b 1218         category associated with ``category_name`` .
CM 1219
1220         If the category named ``category_name`` does not exist in the
1221         introspector the value passed as ``default`` will be returned.
1222
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)."""
412b4a 1228
5e92f3 1229     def categories():
CM 1230         """ Return a sorted sequence of category names known by
1231          this introspector """
1232
57a0d7 1233     def categorized(sort_key=None):
412b4a 1234         """ Get a sequence of tuples in the form ``[(category_name,
CM 1235         [{'introspectable':IIntrospectable, 'related':[sequence of related
1236         IIntrospectables]}, ...])]`` representing all known
57a0d7 1237         introspectables.  If ``sort_key`` is ``None``, each introspectables
412b4a 1238         sequence will be returned in the order the introspectables were added
57a0d7 1239         to the introspector.  Otherwise, sort_key should be a function that
3b5ccb 1240         accepts an IIntrospectable and returns a value from it (ala the
CM 1241         ``key`` function of Python's ``sorted`` callable)."""
1242
1243     def remove(category_name, discriminator):
1244         """ Remove the IIntrospectable related to ``category_name`` and
5e92f3 1245         ``discriminator`` from the introspector, and fix up any relations
CM 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."""
1249
57a9d6 1250     def related(intr):
5e92f3 1251         """ Return a sequence of IIntrospectables related to the
57a9d6 1252         IIntrospectable ``intr``. Return the empty sequence if no relations
CM 1253         for exist."""
5e92f3 1254
CM 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.
1260
1261         This method is not typically called directly, instead it's called
1262         indirectly by :meth:`pyramid.interfaces.IIntrospector.register`"""
3b5ccb 1263
CM 1264     def relate(*pairs):
043ccd 1265         """ Given any number of ``(category_name, discriminator)`` pairs
3b5ccb 1266         passed as positional arguments, relate the associated introspectables
CM 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
5e92f3 1270         pair has already been associated with another.
CM 1271
1272         This method is not typically called directly, instead it's called
1273         indirectly by :meth:`pyramid.interfaces.IIntrospector.register`
1274         """
3b5ccb 1275
CM 1276     def unrelate(*pairs):
043ccd 1277         """ Given any number of ``(category_name, discriminator)`` pairs
3b5ccb 1278         passed as positional arguments, unrelate the associated introspectables
CM 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
5e92f3 1282         pair is not already related to another.
3b5ccb 1283
5e92f3 1284         This method is not typically called directly, instead it's called
CM 1285         indirectly by :meth:`pyramid.interfaces.IIntrospector.register`
1286         """
3b5ccb 1287
CM 1288
1289 class 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
57a0d7 1293     ``collections.MutableMapping`` (the "dictionary interface"), and must be
CM 1294     hashable."""
3b5ccb 1295
5e92f3 1296     title = Attribute('Text title describing this introspectable')
CM 1297     type_name = Attribute('Text type name describing this introspectable')
0c29cf 1298     order = Attribute(
MM 1299         'integer order in which registered with introspector '
1300         '(managed by introspector, usually)'
1301     )
3b5ccb 1302     category_name = Attribute('introspection category name')
0c29cf 1303     discriminator = Attribute(
MM 1304         'introspectable discriminator (within category) ' '(must be hashable)'
1305     )
3b5ccb 1306     discriminator_hash = Attribute('an integer hash of the discriminator')
0c29cf 1307     action_info = Attribute(
MM 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     )
3b5ccb 1313
CM 1314     def relate(category_name, discriminator):
5e92f3 1315         """ Indicate an intent to relate this IIntrospectable with another
CM 1316         IIntrospectable (the one associated with the ``category_name`` and
1317         ``discriminator``) during action execution.
3b5ccb 1318         """
CM 1319
8f6b24 1320     def unrelate(category_name, discriminator):
5e92f3 1321         """ Indicate an intent to break the relationship between this
CM 1322         IIntrospectable with another IIntrospectable (the one associated with
1323         the ``category_name`` and ``discriminator``) during action execution.
1324         """
3b5ccb 1325
57a9d6 1326     def register(introspector, action_info):
35ad08 1327         """ Register this IIntrospectable with an introspector.  This method
CM 1328         is invoked during action execution.  Adds the introspectable and its
57a9d6 1329         relations to the introspector.  ``introspector`` should be an object
CM 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:
35ad08 1334
CM 1335         .. code-block:: python
1336
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))
a54bc1 1344         """  # noqa: E501
35ad08 1345
57a0d7 1346     def __hash__():
CM 1347
1348         """ Introspectables must be hashable.  The typical implementation of
1349         an introsepectable's __hash__ is::
1350
1351           return hash((self.category_name,) + (self.discriminator,))
1352         """
1353
0c29cf 1354
57a9d6 1355 class IActionInfo(Interface):
549cf7 1356     """ Class which provides code introspection capability associated with an
a54bc1 1357     action.  The ParserInfo class used by ZCML implements the same interface.
MM 1358     """
0c29cf 1359
MM 1360     file = Attribute('Filename of action-invoking code as a string')
549cf7 1361     line = Attribute(
d2ed7e 1362         'Starting line number in file (as an integer) of action-invoking code.'
0c29cf 1363         'This will be ``None`` if the value could not be determined.'
MM 1364     )
549cf7 1365
CM 1366     def __str__():
1367         """ Return a representation of the action information (including
1368         source code from file, if possible) """
0c29cf 1369
57a9d6 1370
56df90 1371 class IAssetDescriptor(Interface):
CM 1372     """
1373     Describes an :term:`asset`.
1374     """
1375
1376     def absspec():
1377         """
1378         Returns the absolute asset specification for this asset
1379         (e.g. ``mypackage:templates/foo.pt``).
1380         """
1381
1382     def abspath():
1383         """
1384         Returns an absolute path in the filesystem to the asset.
1385         """
1386
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         """
1392
1393     def isdir():
1394         """
1395         Returns True if the asset is a directory, otherwise returns False.
1396         """
1397
1398     def listdir():
1399         """
1400         Returns iterable of filenames of directory contents.  Raises an
1401         exception if asset is not a directory.
1402         """
1403
1404     def exists():
1405         """
1406         Returns True if asset exists, otherwise returns False.
1407         """
1408
0c29cf 1409
677216 1410 class IJSONAdapter(Interface):
MM 1411     """
1412     Marker interface for objects that can convert an arbitrary object
1413     into a JSON-serializable primitive.
1414     """
1415
0c29cf 1416
a00621 1417 class IPredicateList(Interface):
CM 1418     """ Interface representing a predicate list """
1419
0c29cf 1420
e4b931 1421 class IViewDeriver(Interface):
0c29cf 1422     options = Attribute(
MM 1423         'A list of supported options to be passed to '
1424         ':meth:`pyramid.config.Configurator.add_view`. '
1425         'This attribute is optional.'
1426     )
e4b931 1427
MM 1428     def __call__(view, info):
1429         """
1430         Derive a new view from the supplied view.
1431
1432         View options, package information and registry are available on
1433         ``info``, an instance of :class:`pyramid.interfaces.IViewDeriverInfo`.
1434
1435         The ``view`` is a callable accepting ``(context, request)``.
1436
1437         """
007600 1438
0c29cf 1439
007600 1440 class IViewDeriverInfo(Interface):
MM 1441     """ An object implementing this interface is passed to every
1442     :term:`view deriver` during configuration."""
0c29cf 1443
MM 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     )
007600 1459     predicates = Attribute('The list of predicates active on the view')
a610d0 1460     original_view = Attribute('The original view object being wrapped')
e8c66a 1461     exception_only = Attribute('The view will only be invoked for exceptions')
007600 1462
0c29cf 1463
e4b931 1464 class IViewDerivers(Interface):
MM 1465     """ Interface for view derivers list """
0c29cf 1466
e4b931 1467
2a1ca8 1468 class ICacheBuster(Interface):
CR 1469     """
6e29b4 1470     A cache buster modifies the URL generation machinery for
MM 1471     :meth:`~pyramid.request.Request.static_url`. See :ref:`cache_busting`.
6b88bd 1472
CM 1473     .. versionadded:: 1.6
2a1ca8 1474     """
0c29cf 1475
4d19b8 1476     def __call__(request, subpath, kw):
0445bf 1477         """
40c6bf 1478         Modifies a subpath and/or keyword arguments from which a static asset
4d19b8 1479         URL will be computed during URL generation.
0445bf 1480
6e29b4 1481         The ``subpath`` argument is a path of ``/``-delimited segments that
MM 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
b2fc4a 1486         ``(subpath, kw)`` where ``subpath`` is the relative URL from where the
MM 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.
9d521e 1490
4d19b8 1491         The ``kw`` dictionary contains extra arguments passed to
MM 1492         :meth:`~pyramid.request.Request.static_url` as well as some extra
1493         items that may be usful including:
2a1ca8 1494
4d19b8 1495           - ``pathspec`` is the path specification for the resource
MM 1496             to be cache busted.
1497
1498           - ``rawspec`` is the original location of the file, ignoring
1499             any calls to :meth:`pyramid.config.Configurator.override_asset`.
1500
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
b2fc4a 1507         ``config.override_asset('myapp:static/foo.png', 'themepkg:bar.png')``.
0445bf 1508         """
CR 1509
0c29cf 1510
eb2fee 1511 # configuration phases: a lower phase number means the actions associated
CM 1512 # with this phase will be executed earlier than those with later phase
3171fb 1513 # numbers.  The default phase number is 0, FTR.
eb2fee 1514
568a02 1515 PHASE0_CONFIG = -30
eb2fee 1516 PHASE1_CONFIG = -20
CM 1517 PHASE2_CONFIG = -10
568a02 1518 PHASE3_CONFIG = 0