Michael Merickel
2018-10-15 433efe06191a7007ca8c5bf8fafee5c7c1439ebb
commit | author | age
c151ad 1 from zope.deprecation import deprecated
MM 2
0c1c39 3 from zope.interface import (
CM 4     Attribute,
5     Interface,
6     )
eca67a 7
bc37a5 8 from pyramid.compat import PY2
475532 9
4aa22c 10 # public API interfaces
CM 11
8f45be 12 class IContextFound(Interface):
fd5ae9 13     """ An event type that is emitted after :app:`Pyramid` finds a
8f45be 14     :term:`context` object but before it calls any view code.  See the
c81aad 15     documentation attached to :class:`pyramid.events.ContextFound`
8f45be 16     for more information.
CM 17
012b97 18     .. note::
M 19
20        For backwards compatibility with versions of
fd5ae9 21        :app:`Pyramid` before 1.0, this event interface can also be
c81aad 22        imported as :class:`pyramid.interfaces.IAfterTraversal`.
8f45be 23     """
4aa22c 24     request = Attribute('The request object')
8f45be 25
CM 26 IAfterTraversal = IContextFound
4aa22c 27
d4f5a8 28 class IBeforeTraversal(Interface):
499b78 29     """
4112d6 30     An event type that is emitted after :app:`Pyramid` attempted to find a
BJR 31     route but before it calls any traversal or view code. See the documentation
499b78 32     attached to :class:`pyramid.events.Routefound` for more information.
DS 33     """
34     request = Attribute('The request object')
35
4aa22c 36 class INewRequest(Interface):
fd5ae9 37     """ An event type that is emitted whenever :app:`Pyramid`
8f45be 38     begins to process a new request.  See the documentation attached
c81aad 39     to :class:`pyramid.events.NewRequest` for more information."""
4aa22c 40     request = Attribute('The request object')
012b97 41
4aa22c 42 class INewResponse(Interface):
fd5ae9 43     """ An event type that is emitted whenever any :app:`Pyramid`
8f45be 44     view returns a response. See the
c81aad 45     documentation attached to :class:`pyramid.events.NewResponse`
8f45be 46     for more information."""
eb7ea4 47     request = Attribute('The request object')
4aa22c 48     response = Attribute('The response object')
CM 49
8f45be 50 class IApplicationCreated(Interface):
c6895b 51     """ Event issued when the
aff443 52     :meth:`pyramid.config.Configurator.make_wsgi_app` method
8f45be 53     is called.  See the documentation attached to
c81aad 54     :class:`pyramid.events.ApplicationCreated` for more
8f45be 55     information.
CM 56
012b97 57     .. note::
M 58
59        For backwards compatibility with :app:`Pyramid`
c81aad 60        versions before 1.0, this interface can also be imported as
CM 61        :class:`pyramid.interfaces.IWSGIApplicationCreatedEvent`.
8f45be 62     """
e6c2d2 63     app = Attribute("Created application")
239a93 64
CM 65 IWSGIApplicationCreatedEvent = IApplicationCreated # b /c
4aa22c 66
99edc5 67 class IResponse(Interface):
55241c 68     """ Represents a WSGI response using the WebOb response interface.
TL 69     Some attribute and method documentation of this interface references
70     :rfc:`2616`.
51fb07 71
CM 72     This interface is most famously implemented by
73     :class:`pyramid.response.Response` and the HTTP exception classes in
74     :mod:`pyramid.httpexceptions`."""
75
76     RequestClass = Attribute(
77         """ Alias for :class:`pyramid.request.Request` """)
99edc5 78
CM 79     def __call__(environ, start_response):
51fb07 80         """ :term:`WSGI` call interface, should call the start_response
CM 81         callback and should return an iterable"""
82
83     accept_ranges = Attribute(
84         """Gets and sets and deletes the Accept-Ranges header. For more
85         information on Accept-Ranges see RFC 2616, section 14.5""")
86
87     age = Attribute(
88         """Gets and sets and deletes the Age header. Converts using int.
89         For more information on Age see RFC 2616, section 14.6.""")
90
91     allow = Attribute(
92         """Gets and sets and deletes the Allow header. Converts using
93         list. For more information on Allow see RFC 2616, Section 14.7.""")
94
95     app_iter = Attribute(
96         """Returns the app_iter of the response.
97
98         If body was set, this will create an app_iter from that body
99         (a single-item list)""")
100
101     def app_iter_range(start, stop):
102         """ Return a new app_iter built from the response app_iter that
103         serves up only the given start:stop range. """
104
105     body = Attribute(
106         """The body of the response, as a str. This will read in the entire
107         app_iter if necessary.""")
108
109     body_file = Attribute(
110         """A file-like object that can be used to write to the body. If you
111         passed in a list app_iter, that app_iter will be modified by writes.""")
112
113     cache_control = Attribute(
114         """Get/set/modify the Cache-Control header (RFC 2616 section 14.9)""")
115
116     cache_expires = Attribute(
117         """ Get/set the Cache-Control and Expires headers. This sets the
118             response to expire in the number of seconds passed when set. """)
119
120     charset = Attribute(
121         """Get/set the charset (in the Content-Type)""")
122
123     def conditional_response_app(environ, start_response):
124         """ Like the normal __call__ interface, but checks conditional
125         headers:
126
127         - If-Modified-Since (304 Not Modified; only on GET, HEAD)
128
129         - If-None-Match (304 Not Modified; only on GET, HEAD)
130
131         - Range (406 Partial Content; only on GET, HEAD)"""
132
133     content_disposition = Attribute(
134         """Gets and sets and deletes the Content-Disposition header.
135         For more information on Content-Disposition see RFC 2616 section
136         19.5.1.""")
137
138     content_encoding = Attribute(
139         """Gets and sets and deletes the Content-Encoding header.  For more
140         information about Content-Encoding see RFC 2616 section 14.11.""")
141
142     content_language = Attribute(
143         """Gets and sets and deletes the Content-Language header. Converts
144         using list.  For more information about Content-Language see RFC 2616
145         section 14.12.""")
146
147     content_length = Attribute(
148         """Gets and sets and deletes the Content-Length header. For more
149         information on Content-Length see RFC 2616 section 14.17.
150         Converts using int. """)
151
152     content_location = Attribute(
153         """Gets and sets and deletes the Content-Location header. For more
154         information on Content-Location see RFC 2616 section 14.14.""")
155
156     content_md5 = Attribute(
157         """Gets and sets and deletes the Content-MD5 header. For more
158         information on Content-MD5 see RFC 2616 section 14.14.""")
159
25c64c 160     content_range = Attribute(
51fb07 161         """Gets and sets and deletes the Content-Range header. For more
CM 162         information on Content-Range see section 14.16. Converts using
163         ContentRange object.""")
164
165     content_type = Attribute(
166         """Get/set the Content-Type header (or None), without the charset
167         or any parameters. If you include parameters (or ; at all) when
168         setting the content_type, any existing parameters will be deleted;
169         otherwise they will be preserved.""")
170
171     content_type_params = Attribute(
012b97 172         """A dictionary of all the parameters in the content type.  This is
51fb07 173         not a view, set to change, modifications of the dict would not
CM 174         be applied otherwise.""")
175
176     def copy():
177         """ Makes a copy of the response and returns the copy. """
178
179     date = Attribute(
180         """Gets and sets and deletes the Date header. For more information on
181         Date see RFC 2616 section 14.18. Converts using HTTP date.""")
182
073fac 183     def delete_cookie(name, path='/', domain=None):
51fb07 184         """ Delete a cookie from the client. Note that path and domain must
CM 185         match how the cookie was originally set.  This sets the cookie to the
186         empty string, and max_age=0 so that it should expire immediately. """
187
188     def encode_content(encoding='gzip', lazy=False):
189         """ Encode the content with the given encoding (only gzip and
190         identity are supported)."""
191
192     environ = Attribute(
193         """Get/set the request environ associated with this response,
194         if any.""")
195
196     etag = Attribute(
197         """ Gets and sets and deletes the ETag header. For more information
198         on ETag see RFC 2616 section 14.19. Converts using Entity tag.""")
199
200     expires = Attribute(
201         """ Gets and sets and deletes the Expires header. For more
202         information on Expires see RFC 2616 section 14.21. Converts using
203         HTTP date.""")
204
205     headerlist = Attribute(
206         """ The list of response headers. """)
207
208     headers = Attribute(
209         """ The headers in a dictionary-like object """)
210
211     last_modified = Attribute(
212         """ Gets and sets and deletes the Last-Modified header. For more
213         information on Last-Modified see RFC 2616 section 14.29. Converts
214         using HTTP date.""")
215
216     location = Attribute(
217         """ Gets and sets and deletes the Location header. For more
218         information on Location see RFC 2616 section 14.30.""")
219
220     def md5_etag(body=None, set_content_md5=False):
221         """ Generate an etag for the response object using an MD5 hash of the
222         body (the body parameter, or self.body if not given).  Sets self.etag.
223         If set_content_md5 is True sets self.content_md5 as well """
224
225     def merge_cookies(resp):
226         """ Merge the cookies that were set on this response with the given
227         resp object (which can be any WSGI application).  If the resp is a
228         webob.Response object, then the other object will be modified
229         in-place. """
230
231     pragma = Attribute(
232         """ Gets and sets and deletes the Pragma header. For more information
233         on Pragma see RFC 2616 section 14.32. """)
234
235     request = Attribute(
236         """ Return the request associated with this response if any. """)
237
238     retry_after = Attribute(
239         """ Gets and sets and deletes the Retry-After header. For more
240         information on Retry-After see RFC 2616 section 14.37. Converts
241         using HTTP date or delta seconds.""")
242
243     server = Attribute(
244         """ Gets and sets and deletes the Server header. For more information
245         on Server see RFC216 section 14.38. """)
246
fab055 247     def set_cookie(name, value='', max_age=None, path='/', domain=None,
51fb07 248                    secure=False, httponly=False, comment=None, expires=None,
CM 249                    overwrite=False):
250         """ Set (add) a cookie for the response """
251
252     status = Attribute(
253         """ The status string. """)
254
255     status_int = Attribute(
256         """ The status as an integer """)
257
258     unicode_body = Attribute(
259         """ Get/set the unicode value of the body (using the charset of
260         the Content-Type)""")
261
41662f 262     def unset_cookie(name, strict=True):
51fb07 263         """ Unset a cookie with the given name (remove it from the
CM 264         response)."""
265
266     vary = Attribute(
267         """Gets and sets and deletes the Vary header. For more information
268         on Vary see section 14.44. Converts using list.""")
269
270     www_authenticate = Attribute(
271         """ Gets and sets and deletes the WWW-Authenticate header. For more
272         information on WWW-Authenticate see RFC 2616 section 14.47. Converts
273         using 'parse_auth' and 'serialize_auth'. """)
d96ff9 274
CM 275 class IException(Interface): # not an API
276     """ An interface representing a generic exception """
277
278 class IExceptionResponse(IException, IResponse):
a7e625 279     """ An interface representing a WSGI response which is also an exception
CM 280     object.  Register an exception view using this interface as a ``context``
281     to apply the registered view for all exception types raised by
282     :app:`Pyramid` internally (any exception that inherits from
283     :class:`pyramid.response.Response`, including
99edc5 284     :class:`pyramid.httpexceptions.HTTPNotFound` and
CM 285     :class:`pyramid.httpexceptions.HTTPForbidden`)."""
85093d 286     def prepare(environ):
CM 287         """ Prepares the response for being called as a WSGI application """
d96ff9 288
5c52da 289 class IDict(Interface):
CM 290     # Documentation-only interface
291
292     def __contains__(k):
293         """ Return ``True`` if key ``k`` exists in the dictionary."""
294
295     def __setitem__(k, value):
296         """ Set a key/value pair into the dictionary"""
012b97 297
5c52da 298     def __delitem__(k):
CM 299         """ Delete an item from the dictionary which is passed to the
300         renderer as the renderer globals dictionary."""
012b97 301
5c52da 302     def __getitem__(k):
CM 303         """ Return the value for key ``k`` from the dictionary or raise a
304         KeyError if the key doesn't exist"""
305
306     def __iter__():
307         """ Return an iterator over the keys of this dictionary """
012b97 308
5c52da 309     def get(k, default=None):
CM 310         """ Return the value for key ``k`` from the renderer dictionary, or
311         the default if no such value exists."""
312
313     def items():
314         """ Return a list of [(k,v)] pairs from the dictionary """
315
316     def keys():
317         """ Return a list of keys from the dictionary """
318
319     def values():
320         """ Return a list of values from the dictionary """
321
bc37a5 322     if PY2:
475532 323
CM 324         def iterkeys():
325             """ Return an iterator of keys from the dictionary """
326
327         def iteritems():
328             """ Return an iterator of (k,v) pairs from the dictionary """
329
330         def itervalues():
331             """ Return an iterator of values from the dictionary """
332
333         has_key = __contains__
5c52da 334
CM 335     def pop(k, default=None):
336         """ Pop the key k from the dictionary and return its value.  If k
337         doesn't exist, and default is provided, return the default.  If k
338         doesn't exist and default is not provided, raise a KeyError."""
339
340     def popitem():
341         """ Pop the item with key k from the dictionary and return it as a
342         two-tuple (k, v).  If k doesn't exist, raise a KeyError."""
343
344     def setdefault(k, default=None):
345         """ Return the existing value for key ``k`` in the dictionary.  If no
346          value with ``k`` exists in the dictionary, set the ``default``
347          value into the dictionary under the k name passed.  If a value already
348          existed in the dictionary, return it.  If a value did not exist in
349          the dictionary, return the default"""
012b97 350
5c52da 351     def update(d):
CM 352         """ Update the renderer dictionary with another dictionary ``d``."""
353
354     def clear():
355         """ Clear all values from the dictionary """
356
357 class IBeforeRender(IDict):
a76e99 358     """
7709b1 359     Subscribers to this event may introspect and modify the set of
a76e99 360     :term:`renderer globals` before they are passed to a :term:`renderer`.
5c52da 361     The event object itself provides a dictionary-like interface for adding
CM 362     and removing :term:`renderer globals`.  The keys and values of the
363     dictionary are those globals.  For example::
012b97 364
a76e99 365       from repoze.events import subscriber
CM 366       from pyramid.interfaces import IBeforeRender
367
368       @subscriber(IBeforeRender)
369       def add_global(event):
370           event['mykey'] = 'foo'
371
2033ee 372     .. seealso::
SP 373
374         See also :ref:`beforerender_event`.
a76e99 375     """
9a66aa 376     rendering_val = Attribute('The value returned by a view or passed to a '
CM 377                               '``render`` method for this rendering. '
57144e 378                               'This feature is new in Pyramid 1.2.')
9a66aa 379
b04ae5 380 class IRendererInfo(Interface):
MM 381     """ An object implementing this interface is passed to every
382     :term:`renderer factory` constructor as its only argument (conventionally
383     named ``info``)"""
384     name = Attribute('The value passed by the user as the renderer name')
385     package = Attribute('The "current package" when the renderer '
386                         'configuration statement was found')
387     type = Attribute('The renderer type name')
388     registry = Attribute('The "current" application registry when the '
389                          'renderer was created')
390     settings = Attribute('The deployment settings dictionary related '
391                          'to the current application')
392
ec4691 393     def clone():
MM 394         """ Return a shallow copy that does not share any mutable state."""
395
b04ae5 396 class IRendererFactory(Interface):
MM 397     def __call__(info):
398         """ Return an object that implements
399         :class:`pyramid.interfaces.IRenderer`. ``info`` is an
400         object that implements :class:`pyramid.interfaces.IRendererInfo`.
401         """
402
e26903 403 class IRenderer(Interface):
CM 404     def __call__(value, system):
b04ae5 405         """ Call the renderer with the result of the
e26903 406         view (``value``) passed in and return a result (a string or
CM 407         unicode object useful as a response body).  Values computed by
408         the system are passed by the system in the ``system``
409         parameter, which is a dictionary.  Keys in the dictionary
410         include: ``view`` (the view callable that returned the value),
411         ``renderer_name`` (the template name or simple name of the
412         renderer), ``context`` (the context object passed to the
413         view), and ``request`` (the request object passed to the
414         view)."""
415
416 class ITemplateRenderer(IRenderer):
417     def implementation():
418         """ Return the object that the underlying templating system
419         uses to render the template; it is typically a callable that
420         accepts arbitrary keyword arguments and returns a string or
421         unicode object """
b04ae5 422
MM 423 deprecated(
424     'ITemplateRenderer',
425     'As of Pyramid 1.5 the, "pyramid.interfaces.ITemplateRenderer" interface '
426     'is scheduled to be removed. It was used by the Mako and Chameleon '
c151ad 427     'renderers which have been split into their own packages.'
b04ae5 428     )
e26903 429
8739f5 430 class IViewMapper(Interface):
CM 431     def __call__(self, object):
432         """ Provided with an arbitrary object (a function, class, or
433         instance), returns a callable with the call signature ``(context,
434         request)``.  The callable returned should itself return a Response
435         object.  An IViewMapper is returned by
436         :class:`pyramid.interfaces.IViewMapperFactory`."""
437
438 class IViewMapperFactory(Interface):
439     def __call__(self, **kw):
440         """
441         Return an object which implements
442         :class:`pyramid.interfaces.IViewMapper`.  ``kw`` will be a dictionary
443         containing view-specific arguments, such as ``permission``,
444         ``predicates``, ``attr``, ``renderer``, and other items.  An
445         IViewMapperFactory is used by
446         :meth:`pyramid.config.Configurator.add_view` to provide a plugpoint
447         to extension developers who want to modify potential view callable
448         invocation signatures and response values.
449         """
450
a9fb52 451 class IAuthenticationPolicy(Interface):
c81aad 452     """ An object representing a Pyramid authentication policy. """
fe83c6 453
4aa22c 454     def authenticated_userid(request):
fe83c6 455         """ Return the authenticated :term:`userid` or ``None`` if
MM 456         no authenticated userid can be found. This method of the
457         policy should ensure that a record exists in whatever
458         persistent store is used related to the user (the user
459         should not have been deleted); if a record associated with
460         the current id does not exist in a persistent store, it
461         should return ``None``.
462
463         """
2526d8 464
CM 465     def unauthenticated_userid(request):
fe83c6 466         """ Return the *unauthenticated* userid.  This method
MM 467         performs the same duty as ``authenticated_userid`` but is
468         permitted to return the userid based only on data present
469         in the request; it needn't (and shouldn't) check any
470         persistent store to ensure that the user record related to
471         the request userid exists.
472
473         This method is intended primarily a helper to assist the
474         ``authenticated_userid`` method in pulling credentials out
475         of the request data, abstracting away the specific headers,
476         query strings, etc that are used to authenticate the request.
477
478         """
4aa22c 479
CM 480     def effective_principals(request):
481         """ Return a sequence representing the effective principals
fe83c6 482         typically including the :term:`userid` and any groups belonged
MM 483         to by the current user, always including 'system' groups such
484         as ``pyramid.security.Everyone`` and
485         ``pyramid.security.Authenticated``.
486
487         """
4aa22c 488
c7afe4 489     def remember(request, userid, **kw):
4aa22c 490         """ Return a set of headers suitable for 'remembering' the
fe83c6 491         :term:`userid` named ``userid`` when set in a response.  An
MM 492         individual authentication policy and its consumers can
c62f7d 493         decide on the composition and meaning of ``**kw``.
fe83c6 494
MM 495         """
012b97 496
4aa22c 497     def forget(request):
CM 498         """ Return a set of headers suitable for 'forgetting' the
fe83c6 499         current user on subsequent requests.
MM 500
501         """
4aa22c 502
CM 503 class IAuthorizationPolicy(Interface):
c81aad 504     """ An object representing a Pyramid authorization policy. """
4aa22c 505     def permits(context, principals, permission):
213001 506         """ Return an instance of :class:`pyramid.security.Allowed` if any
MM 507         of the ``principals`` is allowed the ``permission`` in the current
508         ``context``, else return an instance of
509         :class:`pyramid.security.Denied`.
57cc86 510         """
012b97 511
4aa22c 512     def principals_allowed_by_permission(context, permission):
57cc86 513         """ Return a set of principal identifiers allowed by the
CM 514         ``permission`` in ``context``.  This behavior is optional; if you
515         choose to not implement it you should define this method as
516         something which raises a ``NotImplementedError``.  This method
517         will only be called when the
518         ``pyramid.security.principals_allowed_by_permission`` API is
519         used."""
4aa22c 520
5c52da 521 class IMultiDict(IDict): # docs-only interface
2a1c3f 522     """
CM 523     An ordered dictionary that can have multiple values for each key. A
b9a6b3 524     multidict adds the methods ``getall``, ``getone``, ``mixed``, ``extend``,
2a1c3f 525     ``add``, and ``dict_of_lists`` to the normal dictionary interface.  A
CM 526     multidict data structure is used as ``request.POST``, ``request.GET``,
527     and ``request.params`` within an :app:`Pyramid` application.
528     """
529
530     def add(key, value):
531         """ Add the key and value, not overwriting any previous value. """
532
533     def dict_of_lists():
534         """
535         Returns a dictionary where each key is associated with a list of
536         values.
537         """
538
539     def extend(other=None, **kwargs):
540         """ Add a set of keys and values, not overwriting any previous
541         values.  The ``other`` structure may be a list of two-tuples or a
542         dictionary.  If ``**kwargs`` is passed, its value *will* overwrite
543         existing values."""
544
545     def getall(key):
546         """ Return a list of all values matching the key (may be an empty
547         list) """
548
549     def getone(key):
550         """ Get one value matching the key, raising a KeyError if multiple
551         values were found. """
552
553     def mixed():
554         """ Returns a dictionary where the values are either single values,
555         or a list of values when a key/value appears more than once in this
556         dictionary. This is similar to the kind of dictionary often used to
557         represent the variables in a web request. """
d2973d 558
CM 559 # internal interfaces
560
561 class IRequest(Interface):
562     """ Request type interface attached to all request objects """
563
b4843b 564 class ITweens(Interface):
af2323 565     """ Marker interface for utility registration representing the ordered
b4843b 566     set of a configuration's tween factories"""
af2323 567
CM 568 class IRequestHandler(Interface):
569     """ """
570     def __call__(self, request):
0d4963 571         """ Must return a tuple of IReqest, IResponse or raise an exception.
CM 572         The ``request`` argument will be an instance of an object that
573         provides IRequest."""
af2323 574
012b97 575 IRequest.combined = IRequest # for exception view lookups
d2973d 576
d7f34b 577 class IRequestExtensions(Interface):
MM 578     """ Marker interface for storing request extensions (properties and
579     methods) which will be added to the request object."""
580     descriptors = Attribute(
581         """A list of descriptors that will be added to each request.""")
582     methods = Attribute(
583         """A list of methods to be added to each request.""")
74d503 584
d2973d 585 class IRouteRequest(Interface):
CM 586     """ *internal only* interface used as in a utility lookup to find
587     route-specific interfaces.  Not an API."""
588
121f45 589 class IAcceptOrder(Interface):
MM 590     """
591     Marker interface for a list of accept headers with the most important
592     first.
593
594     """
595
b29429 596 class IStaticURLInfo(Interface):
3e2f12 597     """ A policy for generating URLs to static assets """
cda7f6 598     def add(config, name, spec, **extra):
b29429 599         """ Add a new static info registration """
CM 600
601     def generate(path, request, **kw):
602         """ Generate a URL for the given path """
a0b40c 603
6e29b4 604     def add_cache_buster(config, spec, cache_buster):
MM 605         """ Add a new cache buster to a particular set of assets """
606
c8cf22 607 class IResponseFactory(Interface):
da5f5f 608     """ A utility which generates a response """
MM 609     def __call__(request):
610         """ Return a response object implementing IResponse,
611         e.g. :class:`pyramid.response.Response`). It should handle the
612         case when ``request`` is ``None``."""
7de404 613
81a833 614 class IRequestFactory(Interface):
CM 615     """ A utility which generates a request """
616     def __call__(environ):
04cc91 617         """ Return an instance of ``pyramid.request.Request``"""
81a833 618
CM 619     def blank(path):
620         """ Return an empty request object (see
8c6a4c 621         :meth:`pyramid.request.Request.blank`)"""
81a833 622
ff1213 623 class IViewClassifier(Interface):
CM 624     """ *Internal only* marker interface for views."""
625
626 class IExceptionViewClassifier(Interface):
627     """ *Internal only* marker interface for exception views."""
628
7de404 629 class IView(Interface):
CM 630     def __call__(context, request):
99edc5 631         """ Must return an object that implements IResponse. """
d66bfb 632
CM 633 class ISecuredView(IView):
573184 634     """ *Internal only* interface.  Not an API. """
d66bfb 635     def __call_permissive__(context, request):
CM 636         """ Guaranteed-permissive version of __call__ """
637
638     def __permitted__(context, request):
639         """ Return True if view execution will be permitted using the
640         context and request, False otherwise"""
641
642 class IMultiView(ISecuredView):
643     """ *internal only*.  A multiview is a secured view that is a
644     collection of other views.  Each of the views is associated with
645     zero or more predicates.  Not an API."""
ff1213 646     def add(view, predicates, order, accept=None, phash=None):
d66bfb 647         """ Add a view to the multiview. """
5ed24b 648
358dc2 649 class IRootFactory(Interface):
8b1f6e 650     def __call__(request):
CM 651         """ Return a root object based on the request """
dfc2b6 652
CM 653 class IDefaultRootFactory(Interface):
8b1f6e 654     def __call__(request):
dfc2b6 655         """ Return the *default* root object for an application """
612d74 656
4df575 657 class ITraverser(Interface):
8b1f6e 658     def __call__(request):
80a25e 659         """ Return a dictionary with (at least) the keys ``root``,
CM 660         ``context``, ``view_name``, ``subpath``, ``traversed``,
661         ``virtual_root``, and ``virtual_root_path``.  These values are
f426e5 662         typically the result of an object graph traversal.  ``root`` is the
CM 663         physical root object, ``context`` will be a model object,
664         ``view_name`` will be the view name used (a Unicode name),
665         ``subpath`` will be a sequence of Unicode names that followed the
666         view name but were not traversed, ``traversed`` will be a sequence of
667         Unicode names that were traversed (including the virtual root path,
668         if any) ``virtual_root`` will be a model object representing the
669         virtual root (or the physical root if traversal was not performed),
670         and ``virtual_root_path`` will be a sequence representing the virtual
671         root path (a sequence of Unicode names) or ``None`` if traversal was
672         not performed.
80a25e 673
f426e5 674         Extra keys for special purpose functionality can be returned as
80a25e 675         necessary.
CM 676
677         All values returned in the dictionary will be made available
f426e5 678         as attributes of the ``request`` object by the :term:`router`.
80a25e 679         """
93a4f5 680
517d03 681 ITraverserFactory = ITraverser # b / c for 1.0 code
8f8869 682
2466f6 683 class IViewPermission(Interface):
d7e43b 684     def __call__(context, request):
b04ae5 685         """ Return True if the permission allows, return False if it denies.
MM 686         """
2466f6 687
eba6f8 688 class IRouter(Interface):
822653 689     """
MM 690     WSGI application which routes requests to 'view' code based on
691     a view registry.
692
693     """
9dd823 694     registry = Attribute(
eba6f8 695         """Component architecture registry local to this application.""")
012b97 696
822653 697     def request_context(environ):
0bee84 698         """
822653 699         Create a new request context from a WSGI environ.
0bee84 700
822653 701         The request context is used to push/pop the threadlocals required
MM 702         when processing the request. It also contains an initialized
703         :class:`pyramid.interfaces.IRequest` instance using the registered
704         :class:`pyramid.interfaces.IRequestFactory`. The context may be
705         used as a context manager to control the threadlocal lifecycle:
706
707         .. code-block:: python
708
709             with router.request_context(environ) as request:
710                 ...
711
712         Alternatively, the context may be used without the ``with`` statement
713         by manually invoking its ``begin()`` and ``end()`` methods.
714
715         .. code-block:: python
716
717             ctx = router.request_context(environ)
718             request = ctx.begin()
719             try:
720                 ...
721             finally:
722                 ctx.end()
723
0bee84 724         """
MM 725
726     def invoke_request(request):
727         """
728         Invoke the :app:`Pyramid` request pipeline.
729
730         See :ref:`router_chapter` for information on the request pipeline.
822653 731
MM 732         The output should be a :class:`pyramid.interfaces.IResponse` object
733         or a raised exception.
734
0bee84 735         """
MM 736
737 class IExecutionPolicy(Interface):
738     def __call__(environ, router):
739         """
740         This callable triggers the router to process a raw WSGI environ dict
741         into a response and controls the :app:`Pyramid` request pipeline.
742
743         The ``environ`` is the raw WSGI environ.
744
745         The ``router`` is an :class:`pyramid.interfaces.IRouter` object which
746         should be used to create a request object and send it into the
747         processing pipeline.
748
749         The return value should be a :class:`pyramid.interfaces.IResponse`
750         object or an exception that will be handled by WSGI middleware.
751
2e015c 752         The default execution policy simply creates a request and sends it
822653 753         through the pipeline, attempting to render any exception that escapes:
0bee84 754
MM 755         .. code-block:: python
756
757             def simple_execution_policy(environ, router):
822653 758                 with router.request_context(environ) as request:
MM 759                     try:
760                         return router.invoke_request(request)
761                     except Exception:
762                         return request.invoke_exception_view(reraise=True)
0bee84 763         """
MM 764
765 class ISettings(IDict):
c81aad 766     """ Runtime settings utility for pyramid; represents the
8b1f6e 767     deployment settings for the application.  Implements a mapping
CM 768     interface."""
012b97 769
c81aad 770 # this interface, even if it becomes unused within Pyramid, is
cba2e1 771 # imported by other packages (such as traversalwrapper)
cbdc36 772 class ILocation(Interface):
CM 773     """Objects that have a structural location"""
774     __parent__ = Attribute("The parent in the location hierarchy")
775     __name__ = Attribute("The name within the parent")
776
bd39b1 777 class IDebugLogger(Interface):
47b4d3 778     """ Interface representing a PEP 282 logger """
62267e 779
bd39b1 780 ILogger = IDebugLogger # b/c
CM 781
70f1cd 782 class IRoutePregenerator(Interface):
CM 783     def __call__(request, elements, kw):
fb90f0 784
CM 785         """ A pregenerator is a function associated by a developer with a
786         :term:`route`. The pregenerator for a route is called by
787         :meth:`pyramid.request.Request.route_url` in order to adjust the set
788         of arguments passed to it by the user for special purposes, such as
789         Pylons 'subdomain' support.  It will influence the URL returned by
790         ``route_url``.
70f1cd 791
CM 792         A pregenerator should return a two-tuple of ``(elements, kw)``
793         after examining the originals passed to this function, which
794         are the arguments ``(request, elements, kw)``.  The simplest
795         pregenerator is::
796
797             def pregenerator(request, elements, kw):
798                 return elements, kw
799
800         You can employ a pregenerator by passing a ``pregenerator``
801         argument to the
aff443 802         :meth:`pyramid.config.Configurator.add_route`
70f1cd 803         function.
CM 804
805         """
806
74409d 807 class IRoute(Interface):
CM 808     """ Interface representing the type of object returned from
809     ``IRoutesMapper.get_route``"""
810     name = Attribute('The route name')
811     pattern = Attribute('The route pattern')
812     factory = Attribute(
fd5ae9 813         'The :term:`root factory` used by the :app:`Pyramid` router '
74409d 814         'when this route matches (or ``None``)')
CM 815     predicates = Attribute(
816         'A sequence of :term:`route predicate` objects used to '
c337a8 817         'determine if a request matches this route or not after '
74409d 818         'basic pattern matching has been completed.')
70f1cd 819     pregenerator = Attribute('This attribute should either be ``None`` or '
CM 820                              'a callable object implementing the '
821                              '``IRoutePregenerator`` interface')
0445bf 822
74409d 823     def match(path):
CM 824         """
825         If the ``path`` passed to this function can be matched by the
826         ``pattern`` of this route, return a dictionary (the
827         'matchdict'), which will contain keys representing the dynamic
828         segment markers in the pattern mapped to values extracted from
829         the provided ``path``.
830
831         If the ``path`` passed to this function cannot be matched by
832         the ``pattern`` of this route, return ``None``.
833         """
834     def generate(kw):
835         """
836         Generate a URL based on filling in the dynamic segment markers
837         in the pattern using the ``kw`` dictionary provided.
838         """
839
62267e 840 class IRoutesMapper(Interface):
CM 841     """ Interface representing a Routes ``Mapper`` object """
8b1f6e 842     def get_routes():
e725cf 843         """ Return a sequence of Route objects registered in the mapper.
CM 844         Static routes will not be returned in this sequence."""
8b1f6e 845
74409d 846     def has_routes():
CM 847         """ Returns ``True`` if any route has been registered. """
848
849     def get_route(name):
850         """ Returns an ``IRoute`` object if a route with the name ``name``
851         was registered, otherwise return ``None``."""
852
90ed75 853     def connect(name, pattern, factory=None, predicates=(), pregenerator=None,
CM 854                 static=True):
8b1f6e 855         """ Add a new route. """
CM 856
857     def generate(name, kw):
858         """ Generate a URL using the route named ``name`` with the
859         keywords implied by kw"""
860
861     def __call__(request):
74409d 862         """ Return a dictionary containing matching information for
CM 863         the request; the ``route`` key of this dictionary will either
864         be a Route object or ``None`` if no route matched; the
51b2f9 865         ``match`` key will be the matchdict or ``None`` if no route
90ed75 866         matched.  Static routes will not be considered for matching.  """
8b1f6e 867
c51896 868 class IResourceURL(Interface):
db0185 869     virtual_path = Attribute(
CM 870         'The virtual url path of the resource as a string.'
871         )
872     physical_path = Attribute(
873         'The physical url path of the resource as a string.'
874         )
875     virtual_path_tuple = Attribute(
876         'The virtual url path of the resource as a tuple.  (New in 1.5)'
877         )
e744e9 878     physical_path_tuple = Attribute(
db0185 879         'The physical url path of the resource as a tuple. (New in 1.5)'
CM 880         )
c51896 881
bea48e 882 class IPEP302Loader(Interface):
TS 883     """ See http://www.python.org/dev/peps/pep-0302/#id30.
884     """
885     def get_data(path):
886         """ Retrieve data for and arbitrary "files" from storage backend.
887
888         Raise IOError for not found.
889
890         Data is returned as bytes.
891         """
892
893     def is_package(fullname):
894         """ Return True if the module specified by 'fullname' is a package.
895         """
896
897     def get_code(fullname):
898         """ Return the code object for the module identified by 'fullname'.
0445bf 899
bea48e 900         Return 'None' if it's a built-in or extension module.
0445bf 901
bea48e 902         If the loader doesn't have the code object but it does have the source
TS 903         code, return the compiled source code.
904
905         Raise ImportError if the module can't be found by the importer at all.
906         """
907
908     def get_source(fullname):
909         """ Return the source code for the module identified by 'fullname'.
0445bf 910
bea48e 911         Return a string, using newline characters for line endings, or None
TS 912         if the source is not available.
0445bf 913
bea48e 914         Raise ImportError if the module can't be found by the importer at all.
TS 915         """
916
917     def get_filename(fullname):
918         """ Return the value of '__file__' if the named module was loaded.
0445bf 919
bea48e 920         If the module is not found, raise ImportError.
TS 921         """
922
923
924 class IPackageOverrides(IPEP302Loader):
2869fc 925     """ Utility for pkg_resources overrides """
CM 926
a7a6d7 927 # VH_ROOT_KEY is an interface; its imported from other packages (e.g.
CM 928 # traversalwrapper)
ff1213 929 VH_ROOT_KEY = 'HTTP_X_VHM_ROOT'
7534ba 930
CM 931 class ILocalizer(Interface):
932     """ Localizer for a specific language """
012b97 933
7534ba 934 class ILocaleNegotiator(Interface):
CM 935     def __call__(request):
936         """ Return a locale name """
937
938 class ITranslationDirectories(Interface):
939     """ A list object representing all known translation directories
940     for an application"""
d96ff9 941
e25a70 942 class IDefaultPermission(Interface):
CM 943     """ A string object representing the default permission to be used
944     for all view configurations which do not explicitly declare their
945     own."""
968209 946
de3d0c 947 class IDefaultCSRFOptions(Interface):
MM 948     """ An object representing the default CSRF settings to be used for
949     all view configurations which do not explicitly declare their own."""
950     require_csrf = Attribute(
951         'Boolean attribute. If ``True``, then CSRF checks will be enabled by '
952         'default for the view unless overridden.')
953     token = Attribute('The key to be matched in the body of the request.')
954     header = Attribute('The header to be matched with the CSRF token.')
955     safe_methods = Attribute('A set of safe methods that skip CSRF checks.')
17fa5e 956     callback = Attribute('A callback to disable CSRF checks per-request.')
de3d0c 957
968209 958 class ISessionFactory(Interface):
CM 959     """ An interface representing a factory which accepts a request object and
960     returns an ISession object """
961     def __call__(request):
962         """ Return an ISession object """
963
866949 964 class ISession(IDict):
968209 965     """ An interface representing a session (a web session object,
CM 966     usually accessed via ``request.session``.
967
968     Keys and values of a session must be pickleable.
682a9b 969
c31883 970     .. warning::
MM 971
972        In :app:`Pyramid` 2.0 the session will only be required to support
973        types that can be serialized using JSON. It's recommended to switch any
974        session implementations to support only JSON and to only store primitive
975        types in sessions. See :ref:`pickle_session_deprecation` for more
976        information about why this change is being made.
977
682a9b 978     .. versionchanged:: 1.9
MM 979
980        Sessions are no longer required to implement ``get_csrf_token`` and
981        ``new_csrf_token``. CSRF token support was moved to the pluggable
982        :class:`pyramid.interfaces.ICSRFStoragePolicy` configuration hook.
983
968209 984     """
CM 985
986     # attributes
987
988     created = Attribute('Integer representing Epoch time when created.')
989     new = Attribute('Boolean attribute.  If ``True``, the session is new.')
990
991     # special methods
992
993     def invalidate():
994         """ Invalidate the session.  The action caused by
995         ``invalidate`` is implementation-dependent, but it should have
996         the effect of completely dissociating any data stored in the
997         session with the current request.  It might set response
dd4f73 998         values (such as one which clears a cookie), or it might not.
MM 999
1000         An invalidated session may be used after the call to ``invalidate``
1001         with the effect that a new session is created to store the data. This
1002         enables workflows requiring an entirely new session, such as in the
1003         case of changing privilege levels or preventing fixation attacks.
1004         """
968209 1005
CM 1006     def changed():
1007         """ Mark the session as changed. A user of a session should
1008         call this method after he or she mutates a mutable object that
1009         is *a value of the session* (it should not be required after
1010         mutating the session itself).  For example, if the user has
1011         stored a dictionary in the session under the key ``foo``, and
1012         he or she does ``session['foo'] = {}``, ``changed()`` needn't
1013         be called.  However, if subsequently he or she does
1014         ``session['foo']['a'] = 1``, ``changed()`` must be called for
1015         the sessioning machinery to notice the mutation of the
1016         internal dictionary."""
1017
6f6d36 1018     def flash(msg, queue='', allow_duplicate=True):
CM 1019         """ Push a flash message onto the end of the flash queue represented
1020         by ``queue``.  An alternate flash message queue can used by passing
1021         an optional ``queue``, which must be a string.  If
1022         ``allow_duplicate`` is false, if the ``msg`` already exists in the
bfb395 1023         queue, it will not be re-added."""
4df636 1024
6f6d36 1025     def pop_flash(queue=''):
CM 1026         """ Pop a queue from the flash storage.  The queue is removed from
1027         flash storage after this message is called.  The queue is returned;
1028         it is a list of flash messages added by
be03f7 1029         :meth:`pyramid.interfaces.ISession.flash`"""
6f6d36 1030
CM 1031     def peek_flash(queue=''):
1032         """ Peek at a queue in the flash storage.  The queue remains in
1033         flash storage after this message is called.  The queue is returned;
1034         it is a list of flash messages added by
be03f7 1035         :meth:`pyramid.interfaces.ISession.flash`
319793 1036         """
CM 1037
1038
fe0d22 1039 class ICSRFStoragePolicy(Interface):
a2c7c7 1040     """ An object that offers the ability to verify CSRF tokens and generate
682a9b 1041     new ones."""
a2c7c7 1042
MW 1043     def new_csrf_token(request):
682a9b 1044         """ Create and return a new, random cross-site request forgery
MM 1045         protection token. The token will be an ascii-compatible unicode
1046         string.
1047
1048         """
a2c7c7 1049
MW 1050     def get_csrf_token(request):
1051         """ Return a cross-site request forgery protection token.  It
682a9b 1052         will be an ascii-compatible unicode string.  If a token was previously
MM 1053         set for this user via ``new_csrf_token``, that token will be returned.
1054         If no CSRF token was previously set, ``new_csrf_token`` will be
1055         called, which will create and set a token, and this token will be
1056         returned.
eb2fee 1057
a2c7c7 1058         """
MW 1059
3f14d6 1060     def check_csrf_token(request, token):
MM 1061         """ Determine if the supplied ``token`` is valid. Most implementations
1062         should simply compare the ``token`` to the current value of
1063         ``get_csrf_token`` but it is possible to verify the token using
1064         any mechanism necessary using this method.
1065
1066         Returns ``True`` if the ``token`` is valid, otherwise ``False``.
1067
1068         """
1069
a2c7c7 1070
3b5ccb 1071 class IIntrospector(Interface):
CM 1072     def get(category_name, discriminator, default=None):
1073         """ Get the IIntrospectable related to the category_name and the
1074         discriminator (or discriminator hash) ``discriminator``.  If it does
8a32e3 1075         not exist in the introspector, return the value of ``default`` """
3b5ccb 1076
79f34b 1077     def get_category(category_name, default=None, sort_key=None):
412b4a 1078         """ Get a sequence of dictionaries in the form
CM 1079         ``[{'introspectable':IIntrospectable, 'related':[sequence of related
1080         IIntrospectables]}, ...]`` where each introspectable is part of the
79f34b 1081         category associated with ``category_name`` .
CM 1082
1083         If the category named ``category_name`` does not exist in the
1084         introspector the value passed as ``default`` will be returned.
1085
1086         If ``sort_key`` is ``None``, the sequence will be returned in the
1087         order the introspectables were added to the introspector.  Otherwise,
1088         sort_key should be a function that accepts an IIntrospectable and
1089         returns a value from it (ala the ``key`` function of Python's
1090         ``sorted`` callable)."""
412b4a 1091
5e92f3 1092     def categories():
CM 1093         """ Return a sorted sequence of category names known by
1094          this introspector """
1095
57a0d7 1096     def categorized(sort_key=None):
412b4a 1097         """ Get a sequence of tuples in the form ``[(category_name,
CM 1098         [{'introspectable':IIntrospectable, 'related':[sequence of related
1099         IIntrospectables]}, ...])]`` representing all known
57a0d7 1100         introspectables.  If ``sort_key`` is ``None``, each introspectables
412b4a 1101         sequence will be returned in the order the introspectables were added
57a0d7 1102         to the introspector.  Otherwise, sort_key should be a function that
3b5ccb 1103         accepts an IIntrospectable and returns a value from it (ala the
CM 1104         ``key`` function of Python's ``sorted`` callable)."""
1105
1106     def remove(category_name, discriminator):
1107         """ Remove the IIntrospectable related to ``category_name`` and
5e92f3 1108         ``discriminator`` from the introspector, and fix up any relations
CM 1109         that the introspectable participates in. This method will not raise
1110         an error if an introspectable related to the category name and
1111         discriminator does not exist."""
1112
57a9d6 1113     def related(intr):
5e92f3 1114         """ Return a sequence of IIntrospectables related to the
57a9d6 1115         IIntrospectable ``intr``. Return the empty sequence if no relations
CM 1116         for exist."""
5e92f3 1117
CM 1118     def add(intr):
1119         """ Add the IIntrospectable ``intr`` (use instead of
1120         :meth:`pyramid.interfaces.IIntrospector.add` when you have a custom
1121         IIntrospectable). Replaces any existing introspectable registered
1122         using the same category/discriminator.
1123
1124         This method is not typically called directly, instead it's called
1125         indirectly by :meth:`pyramid.interfaces.IIntrospector.register`"""
3b5ccb 1126
CM 1127     def relate(*pairs):
043ccd 1128         """ Given any number of ``(category_name, discriminator)`` pairs
3b5ccb 1129         passed as positional arguments, relate the associated introspectables
CM 1130         to each other. The introspectable related to each pair must have
1131         already been added via ``.add`` or ``.add_intr``; a :exc:`KeyError`
1132         will result if this is not true.  An error will not be raised if any
5e92f3 1133         pair has already been associated with another.
CM 1134
1135         This method is not typically called directly, instead it's called
1136         indirectly by :meth:`pyramid.interfaces.IIntrospector.register`
1137         """
3b5ccb 1138
CM 1139     def unrelate(*pairs):
043ccd 1140         """ Given any number of ``(category_name, discriminator)`` pairs
3b5ccb 1141         passed as positional arguments, unrelate the associated introspectables
CM 1142         from each other. The introspectable related to each pair must have
1143         already been added via ``.add`` or ``.add_intr``; a :exc:`KeyError`
1144         will result if this is not true.  An error will not be raised if any
5e92f3 1145         pair is not already related to another.
3b5ccb 1146
5e92f3 1147         This method is not typically called directly, instead it's called
CM 1148         indirectly by :meth:`pyramid.interfaces.IIntrospector.register`
1149         """
3b5ccb 1150
CM 1151
1152 class IIntrospectable(Interface):
1153     """ An introspectable object used for configuration introspection.  In
1154     addition to the methods below, objects which implement this interface
1155     must also implement all the methods of Python's
57a0d7 1156     ``collections.MutableMapping`` (the "dictionary interface"), and must be
CM 1157     hashable."""
3b5ccb 1158
5e92f3 1159     title = Attribute('Text title describing this introspectable')
CM 1160     type_name = Attribute('Text type name describing this introspectable')
1161     order = Attribute('integer order in which registered with introspector '
522405 1162                       '(managed by introspector, usually)')
3b5ccb 1163     category_name = Attribute('introspection category name')
CM 1164     discriminator = Attribute('introspectable discriminator (within category) '
1165                               '(must be hashable)')
1166     discriminator_hash = Attribute('an integer hash of the discriminator')
522405 1167     action_info = Attribute('An IActionInfo object representing the caller '
CM 1168                             'that invoked the creation of this introspectable '
1169                             '(usually a sentinel until updated during '
1170                             'self.register)')
3b5ccb 1171
CM 1172     def relate(category_name, discriminator):
5e92f3 1173         """ Indicate an intent to relate this IIntrospectable with another
CM 1174         IIntrospectable (the one associated with the ``category_name`` and
1175         ``discriminator``) during action execution.
3b5ccb 1176         """
CM 1177
8f6b24 1178     def unrelate(category_name, discriminator):
5e92f3 1179         """ Indicate an intent to break the relationship between this
CM 1180         IIntrospectable with another IIntrospectable (the one associated with
1181         the ``category_name`` and ``discriminator``) during action execution.
1182         """
3b5ccb 1183
57a9d6 1184     def register(introspector, action_info):
35ad08 1185         """ Register this IIntrospectable with an introspector.  This method
CM 1186         is invoked during action execution.  Adds the introspectable and its
57a9d6 1187         relations to the introspector.  ``introspector`` should be an object
CM 1188         implementing IIntrospector.  ``action_info`` should be a object
1189         implementing the interface :class:`pyramid.interfaces.IActionInfo`
1190         representing the call that registered this introspectable.
1191         Pseudocode for an implementation of this method:
35ad08 1192
CM 1193         .. code-block:: python
1194
1195             def register(self, introspector, action_info):
1196                 self.action_info = action_info
1197                 introspector.add(self)
1198                 for methodname, category_name, discriminator in self._relations:
1199                     method = getattr(introspector, methodname)
1200                     method((i.category_name, i.discriminator),
1201                            (category_name, discriminator))
1202         """
1203
57a0d7 1204     def __hash__():
CM 1205
1206         """ Introspectables must be hashable.  The typical implementation of
1207         an introsepectable's __hash__ is::
1208
1209           return hash((self.category_name,) + (self.discriminator,))
1210         """
1211
57a9d6 1212 class IActionInfo(Interface):
549cf7 1213     """ Class which provides code introspection capability associated with an
CM 1214     action.  The ParserInfo class used by ZCML implements the same interface."""
1215     file = Attribute(
d2ed7e 1216         'Filename of action-invoking code as a string')
549cf7 1217     line = Attribute(
d2ed7e 1218         'Starting line number in file (as an integer) of action-invoking code.'
CM 1219         'This will be ``None`` if the value could not be determined.')
549cf7 1220
CM 1221     def __str__():
1222         """ Return a representation of the action information (including
1223         source code from file, if possible) """
57a9d6 1224
56df90 1225 class IAssetDescriptor(Interface):
CM 1226     """
1227     Describes an :term:`asset`.
1228     """
1229
1230     def absspec():
1231         """
1232         Returns the absolute asset specification for this asset
1233         (e.g. ``mypackage:templates/foo.pt``).
1234         """
1235
1236     def abspath():
1237         """
1238         Returns an absolute path in the filesystem to the asset.
1239         """
1240
1241     def stream():
1242         """
1243         Returns an input stream for reading asset contents.  Raises an
1244         exception if the asset is a directory or does not exist.
1245         """
1246
1247     def isdir():
1248         """
1249         Returns True if the asset is a directory, otherwise returns False.
1250         """
1251
1252     def listdir():
1253         """
1254         Returns iterable of filenames of directory contents.  Raises an
1255         exception if asset is not a directory.
1256         """
1257
1258     def exists():
1259         """
1260         Returns True if asset exists, otherwise returns False.
1261         """
1262
677216 1263 class IJSONAdapter(Interface):
MM 1264     """
1265     Marker interface for objects that can convert an arbitrary object
1266     into a JSON-serializable primitive.
1267     """
1268
a00621 1269 class IPredicateList(Interface):
CM 1270     """ Interface representing a predicate list """
1271
e4b931 1272 class IViewDeriver(Interface):
0b0f7e 1273     options = Attribute('A list of supported options to be passed to '
e4b931 1274                         ':meth:`pyramid.config.Configurator.add_view`. '
MM 1275                         'This attribute is optional.')
1276
1277     def __call__(view, info):
1278         """
1279         Derive a new view from the supplied view.
1280
1281         View options, package information and registry are available on
1282         ``info``, an instance of :class:`pyramid.interfaces.IViewDeriverInfo`.
1283
1284         The ``view`` is a callable accepting ``(context, request)``.
1285
1286         """
007600 1287
MM 1288 class IViewDeriverInfo(Interface):
1289     """ An object implementing this interface is passed to every
1290     :term:`view deriver` during configuration."""
2160ce 1291     registry = Attribute('The "current" application registry where the '
007600 1292                          'view was created')
2160ce 1293     package = Attribute('The "current package" where the view '
007600 1294                         'configuration statement was found')
MM 1295     settings = Attribute('The deployment settings dictionary related '
1296                          'to the current application')
1297     options = Attribute('The view options passed to the view, including any '
1298                         'default values that were not overriden')
1299     predicates = Attribute('The list of predicates active on the view')
a610d0 1300     original_view = Attribute('The original view object being wrapped')
e8c66a 1301     exception_only = Attribute('The view will only be invoked for exceptions')
007600 1302
e4b931 1303 class IViewDerivers(Interface):
MM 1304     """ Interface for view derivers list """
1305
2a1ca8 1306 class ICacheBuster(Interface):
CR 1307     """
6e29b4 1308     A cache buster modifies the URL generation machinery for
MM 1309     :meth:`~pyramid.request.Request.static_url`. See :ref:`cache_busting`.
6b88bd 1310
CM 1311     .. versionadded:: 1.6
2a1ca8 1312     """
4d19b8 1313     def __call__(request, subpath, kw):
0445bf 1314         """
40c6bf 1315         Modifies a subpath and/or keyword arguments from which a static asset
4d19b8 1316         URL will be computed during URL generation.
0445bf 1317
6e29b4 1318         The ``subpath`` argument is a path of ``/``-delimited segments that
MM 1319         represent the portion of the asset URL which is used to find the asset.
1320         The ``kw`` argument is a dict of keywords that are to be passed
1321         eventually to :meth:`~pyramid.request.Request.static_url` for URL
1322         generation.  The return value should be a two-tuple of
b2fc4a 1323         ``(subpath, kw)`` where ``subpath`` is the relative URL from where the
MM 1324         file is served and ``kw`` is the same input argument. The return value
1325         should be modified to include the cache bust token in the generated
1326         URL.
9d521e 1327
4d19b8 1328         The ``kw`` dictionary contains extra arguments passed to
MM 1329         :meth:`~pyramid.request.Request.static_url` as well as some extra
1330         items that may be usful including:
2a1ca8 1331
4d19b8 1332           - ``pathspec`` is the path specification for the resource
MM 1333             to be cache busted.
1334
1335           - ``rawspec`` is the original location of the file, ignoring
1336             any calls to :meth:`pyramid.config.Configurator.override_asset`.
1337
1338         The ``pathspec`` and ``rawspec`` values are only different in cases
1339         where an asset has been mounted into a virtual location using
1340         :meth:`pyramid.config.Configurator.override_asset`. For example, with
1341         a call to ``request.static_url('myapp:static/foo.png'), the
1342         ``pathspec`` is ``myapp:static/foo.png`` whereas the ``rawspec`` may
1343         be ``themepkg:bar.png``, assuming a call to
b2fc4a 1344         ``config.override_asset('myapp:static/foo.png', 'themepkg:bar.png')``.
0445bf 1345         """
CR 1346
eb2fee 1347 # configuration phases: a lower phase number means the actions associated
CM 1348 # with this phase will be executed earlier than those with later phase
3171fb 1349 # numbers.  The default phase number is 0, FTR.
eb2fee 1350
568a02 1351 PHASE0_CONFIG = -30
eb2fee 1352 PHASE1_CONFIG = -20
CM 1353 PHASE2_CONFIG = -10
568a02 1354 PHASE3_CONFIG = 0