pyramid.interfaces¶
Other Interfaces¶
- interface
IAuthenticationPolicy[source]¶An object representing a Pyramid authentication policy.
remember(request, userid, **kw)¶Return a set of headers suitable for 'remembering' the userid named
useridwhen set in a response. An individual authentication policy and its consumers can decide on the composition and meaning of**kw.
authenticated_userid(request)¶Return the authenticated userid or
Noneif no authenticated userid can be found. This method of the policy should ensure that a record exists in whatever persistent store is used related to the user (the user should not have been deleted); if a record associated with the current id does not exist in a persistent store, it should returnNone.
unauthenticated_userid(request)¶Return the unauthenticated userid. This method performs the same duty as
authenticated_useridbut is permitted to return the userid based only on data present in the request; it needn't (and shouldn't) check any persistent store to ensure that the user record related to the request userid exists.This method is intended primarily a helper to assist the
authenticated_useridmethod in pulling credentials out of the request data, abstracting away the specific headers, query strings, etc that are used to authenticate the request.
forget(request)¶Return a set of headers suitable for 'forgetting' the current user on subsequent requests.
- interface
IAuthorizationPolicy[source]¶An object representing a Pyramid authorization policy.
principals_allowed_by_permission(context, permission)¶Return a set of principal identifiers allowed by the
permissionincontext. This behavior is optional; if you choose to not implement it you should define this method as something which raises aNotImplementedError. This method will only be called when thepyramid.security.principals_allowed_by_permissionAPI is used.
permits(context, principals, permission)¶Return an instance of
pyramid.security.Allowedif any of theprincipalsis allowed thepermissionin the currentcontext, else return an instance ofpyramid.security.Denied.
- interface
IExceptionResponse[source]¶Extends:
pyramid.interfaces.IException,pyramid.interfaces.IResponseAn interface representing a WSGI response which is also an exception object. Register an exception view using this interface as a
contextto apply the registered view for all exception types raised by Pyramid internally (any exception that inherits frompyramid.response.Response, includingpyramid.httpexceptions.HTTPNotFoundandpyramid.httpexceptions.HTTPForbidden).
prepare(environ)¶Prepares the response for being called as a WSGI application
- interface
IRoute[source]¶Interface representing the type of object returned from
IRoutesMapper.get_route
match(path)¶If the
pathpassed to this function can be matched by thepatternof this route, return a dictionary (the 'matchdict'), which will contain keys representing the dynamic segment markers in the pattern mapped to values extracted from the providedpath.If the
pathpassed to this function cannot be matched by thepatternof this route, returnNone.
pattern¶The route pattern
pregenerator¶This attribute should either be
Noneor a callable object implementing theIRoutePregeneratorinterface
factory¶The root factory used by the Pyramid router when this route matches (or
None)
predicates¶A sequence of route predicate objects used to determine if a request matches this route or not after basic pattern matching has been completed.
name¶The route name
generate(kw)¶Generate a URL based on filling in the dynamic segment markers in the pattern using the
kwdictionary provided.
- interface
IRoutePregenerator[source]¶
__call__(request, elements, kw)¶A pregenerator is a function associated by a developer with a route. The pregenerator for a route is called by
pyramid.request.Request.route_url()in order to adjust the set of arguments passed to it by the user for special purposes, such as Pylons 'subdomain' support. It will influence the URL returned byroute_url.A pregenerator should return a two-tuple of
(elements, kw)after examining the originals passed to this function, which are the arguments(request, elements, kw). The simplest pregenerator is:def pregenerator(request, elements, kw): return elements, kwYou can employ a pregenerator by passing a
pregeneratorargument to thepyramid.config.Configurator.add_route()function.
- interface
ICSRFStoragePolicy[source]¶An object that offers the ability to verify CSRF tokens and generate new ones.
check_csrf_token(request, token)¶Determine if the supplied
tokenis valid. Most implementations should simply compare thetokento the current value ofget_csrf_tokenbut it is possible to verify the token using any mechanism necessary using this method.Returns
Trueif thetokenis valid, otherwiseFalse.
get_csrf_token(request)¶Return a cross-site request forgery protection token. It will be an ascii-compatible unicode string. If a token was previously set for this user via
new_csrf_token, that token will be returned. If no CSRF token was previously set,new_csrf_tokenwill be called, which will create and set a token, and this token will be returned.
new_csrf_token(request)¶Create and return a new, random cross-site request forgery protection token. The token will be an ascii-compatible unicode string.
- interface
ISession[source]¶Extends:
pyramid.interfaces.IDictAn interface representing a session (a web session object, usually accessed via
request.session.Keys and values of a session must be pickleable.
Changed in version 1.9: Sessions are no longer required to implement
get_csrf_tokenandnew_csrf_token. CSRF token support was moved to the pluggablepyramid.interfaces.ICSRFStoragePolicyconfiguration hook.
peek_flash(queue='')¶Peek at a queue in the flash storage. The queue remains in flash storage after this message is called. The queue is returned; it is a list of flash messages added by
pyramid.interfaces.ISession.flash()
invalidate()¶Invalidate the session. The action caused by
invalidateis implementation-dependent, but it should have the effect of completely dissociating any data stored in the session with the current request. It might set response values (such as one which clears a cookie), or it might not.An invalidated session may be used after the call to
invalidatewith the effect that a new session is created to store the data. This enables workflows requiring an entirely new session, such as in the case of changing privilege levels or preventing fixation attacks.
flash(msg, queue='', allow_duplicate=True)¶Push a flash message onto the end of the flash queue represented by
queue. An alternate flash message queue can used by passing an optionalqueue, which must be a string. Ifallow_duplicateis false, if themsgalready exists in the queue, it will not be re-added.
new¶Boolean attribute. If
True, the session is new.
pop_flash(queue='')¶Pop a queue from the flash storage. The queue is removed from flash storage after this message is called. The queue is returned; it is a list of flash messages added by
pyramid.interfaces.ISession.flash()
created¶Integer representing Epoch time when created.
changed()¶Mark the session as changed. A user of a session should call this method after he or she mutates a mutable object that is a value of the session (it should not be required after mutating the session itself). For example, if the user has stored a dictionary in the session under the key
foo, and he or she doessession['foo'] = {},changed()needn't be called. However, if subsequently he or she doessession['foo']['a'] = 1,changed()must be called for the sessioning machinery to notice the mutation of the internal dictionary.
- interface
ISessionFactory[source]¶An interface representing a factory which accepts a request object and returns an ISession object
__call__(request)¶Return an ISession object
- interface
IRendererInfo[source]¶An object implementing this interface is passed to every renderer factory constructor as its only argument (conventionally named
info)
type¶The renderer type name
settings¶The deployment settings dictionary related to the current application
clone()¶Return a shallow copy that does not share any mutable state.
package¶The "current package" when the renderer configuration statement was found
name¶The value passed by the user as the renderer name
registry¶The "current" application registry when the renderer was created
- interface
IRendererFactory[source]¶
__call__(info)¶Return an object that implements
pyramid.interfaces.IRenderer.infois an object that implementspyramid.interfaces.IRendererInfo.
- interface
IRenderer[source]¶
__call__(value, system)¶Call the renderer with the result of the view (
value) passed in and return a result (a string or unicode object useful as a response body). Values computed by the system are passed by the system in thesystemparameter, which is a dictionary. Keys in the dictionary include:view(the view callable that returned the value),renderer_name(the template name or simple name of the renderer),context(the context object passed to the view), andrequest(the request object passed to the view).
- interface
IRequestFactory[source]¶A utility which generates a request
blank(path)¶Return an empty request object (see
pyramid.request.Request.blank())
__call__(environ)¶Return an instance of
pyramid.request.Request
- interface
IResponseFactory[source]¶A utility which generates a response
__call__(request)¶Return a response object implementing IResponse, e.g.
pyramid.response.Response). It should handle the case whenrequestisNone.
- interface
IRouter[source]¶WSGI application which routes requests to 'view' code based on a view registry.
invoke_request(request)¶Invoke the Pyramid request pipeline.
See Request Processing for information on the request pipeline.
The output should be a
pyramid.interfaces.IResponseobject or a raised exception.
request_context(environ)¶Create a new request context from a WSGI environ.
The request context is used to push/pop the threadlocals required when processing the request. It also contains an initialized
pyramid.interfaces.IRequestinstance using the registeredpyramid.interfaces.IRequestFactory. The context may be used as a context manager to control the threadlocal lifecycle:with router.request_context(environ) as request: ...Alternatively, the context may be used without the
withstatement by manually invoking itsbegin()andend()methods.ctx = router.request_context(environ) request = ctx.begin() try: ... finally: ctx.end()
registry¶Component architecture registry local to this application.
- interface
IViewMapperFactory[source]¶
__call__(self, **kw)¶Return an object which implements
pyramid.interfaces.IViewMapper.kwwill be a dictionary containing view-specific arguments, such aspermission,predicates,attr,renderer, and other items. An IViewMapperFactory is used bypyramid.config.Configurator.add_view()to provide a plugpoint to extension developers who want to modify potential view callable invocation signatures and response values.
- interface
IViewMapper[source]¶
__call__(self, object)¶Provided with an arbitrary object (a function, class, or instance), returns a callable with the call signature
(context, request). The callable returned should itself return a Response object. An IViewMapper is returned bypyramid.interfaces.IViewMapperFactory.
- interface
IDict[source]¶
pop(k, default=None)¶Pop the key k from the dictionary and return its value. If k doesn't exist, and default is provided, return the default. If k doesn't exist and default is not provided, raise a KeyError.
__contains__(k)¶Return
Trueif keykexists in the dictionary.
__iter__()¶Return an iterator over the keys of this dictionary
get(k, default=None)¶Return the value for key
kfrom the renderer dictionary, or the default if no such value exists.
clear()¶Clear all values from the dictionary
keys()¶Return a list of keys from the dictionary
__getitem__(k)¶Return the value for key
kfrom the dictionary or raise a KeyError if the key doesn't exist
__delitem__(k)¶Delete an item from the dictionary which is passed to the renderer as the renderer globals dictionary.
items()¶Return a list of [(k,v)] pairs from the dictionary
values()¶Return a list of values from the dictionary
popitem()¶Pop the item with key k from the dictionary and return it as a two-tuple (k, v). If k doesn't exist, raise a KeyError.
update(d)¶Update the renderer dictionary with another dictionary
d.
setdefault(k, default=None)¶Return the existing value for key
kin the dictionary. If no value withkexists in the dictionary, set thedefaultvalue into the dictionary under the k name passed. If a value already existed in the dictionary, return it. If a value did not exist in the dictionary, return the default
__setitem__(k, value)¶Set a key/value pair into the dictionary
- interface
IMultiDict[source]¶Extends:
pyramid.interfaces.IDictAn ordered dictionary that can have multiple values for each key. A multidict adds the methods
getall,getone,mixed,extend,add, anddict_of_liststo the normal dictionary interface. A multidict data structure is used asrequest.POST,request.GET, andrequest.paramswithin an Pyramid application.
mixed()¶Returns a dictionary where the values are either single values, or a list of values when a key/value appears more than once in this dictionary. This is similar to the kind of dictionary often used to represent the variables in a web request.
dict_of_lists()¶Returns a dictionary where each key is associated with a list of values.
getone(key)¶Get one value matching the key, raising a KeyError if multiple values were found.
getall(key)¶Return a list of all values matching the key (may be an empty list)
add(key, value)¶Add the key and value, not overwriting any previous value.
extend(other=None, **kwargs)¶Add a set of keys and values, not overwriting any previous values. The
otherstructure may be a list of two-tuples or a dictionary. If**kwargsis passed, its value will overwrite existing values.
- interface
IResponse[source]¶Represents a WSGI response using the WebOb response interface. Some attribute and method documentation of this interface references RFC 2616.
This interface is most famously implemented by
pyramid.response.Responseand the HTTP exception classes inpyramid.httpexceptions.
body_file¶A file-like object that can be used to write to the body. If you passed in a list app_iter, that app_iter will be modified by writes.
encode_content(encoding='gzip', lazy=False)¶Encode the content with the given encoding (only gzip and identity are supported).
headers¶The headers in a dictionary-like object
environ¶Get/set the request environ associated with this response, if any.
copy()¶Makes a copy of the response and returns the copy.
app_iter¶Returns the app_iter of the response.
If body was set, this will create an app_iter from that body (a single-item list)
retry_after¶Gets and sets and deletes the Retry-After header. For more information on Retry-After see RFC 2616 section 14.37. Converts using HTTP date or delta seconds.
app_iter_range(start, stop)¶Return a new app_iter built from the response app_iter that serves up only the given start:stop range.
status_int¶The status as an integer
age¶Gets and sets and deletes the Age header. Converts using int. For more information on Age see RFC 2616, section 14.6.
content_encoding¶Gets and sets and deletes the Content-Encoding header. For more information about Content-Encoding see RFC 2616 section 14.11.
status¶The status string.
content_location¶Gets and sets and deletes the Content-Location header. For more information on Content-Location see RFC 2616 section 14.14.
allow¶Gets and sets and deletes the Allow header. Converts using list. For more information on Allow see RFC 2616, Section 14.7.
cache_control¶Get/set/modify the Cache-Control header (RFC 2616 section 14.9)
Unset a cookie with the given name (remove it from the response).
server¶Gets and sets and deletes the Server header. For more information on Server see RFC216 section 14.38.
body¶The body of the response, as a str. This will read in the entire app_iter if necessary.
pragma¶Gets and sets and deletes the Pragma header. For more information on Pragma see RFC 2616 section 14.32.
content_type¶Get/set the Content-Type header (or None), without the charset or any parameters. If you include parameters (or ; at all) when setting the content_type, any existing parameters will be deleted; otherwise they will be preserved.
content_range¶Gets and sets and deletes the Content-Range header. For more information on Content-Range see section 14.16. Converts using ContentRange object.
request¶Return the request associated with this response if any.
content_md5¶Gets and sets and deletes the Content-MD5 header. For more information on Content-MD5 see RFC 2616 section 14.14.
unicode_body¶Get/set the unicode value of the body (using the charset of the Content-Type)
last_modified¶Gets and sets and deletes the Last-Modified header. For more information on Last-Modified see RFC 2616 section 14.29. Converts using HTTP date.
accept_ranges¶Gets and sets and deletes the Accept-Ranges header. For more information on Accept-Ranges see RFC 2616, section 14.5
Merge the cookies that were set on this response with the given resp object (which can be any WSGI application). If the resp is a webob.Response object, then the other object will be modified in-place.
conditional_response_app(environ, start_response)¶Like the normal __call__ interface, but checks conditional headers:
- If-Modified-Since (304 Not Modified; only on GET, HEAD)
- If-None-Match (304 Not Modified; only on GET, HEAD)
- Range (406 Partial Content; only on GET, HEAD)
expires¶Gets and sets and deletes the Expires header. For more information on Expires see RFC 2616 section 14.21. Converts using HTTP date.
etag¶Gets and sets and deletes the ETag header. For more information on ETag see RFC 2616 section 14.19. Converts using Entity tag.
vary¶Gets and sets and deletes the Vary header. For more information on Vary see section 14.44. Converts using list.
content_type_params¶A dictionary of all the parameters in the content type. This is not a view, set to change, modifications of the dict would not be applied otherwise.
md5_etag(body=None, set_content_md5=False)¶Generate an etag for the response object using an MD5 hash of the body (the body parameter, or self.body if not given). Sets self.etag. If set_content_md5 is True sets self.content_md5 as well
cache_expires¶Get/set the Cache-Control and Expires headers. This sets the response to expire in the number of seconds passed when set.
__call__(environ, start_response)¶WSGI call interface, should call the start_response callback and should return an iterable
content_disposition¶Gets and sets and deletes the Content-Disposition header. For more information on Content-Disposition see RFC 2616 section 19.5.1.
location¶Gets and sets and deletes the Location header. For more information on Location see RFC 2616 section 14.30.
content_language¶Gets and sets and deletes the Content-Language header. Converts using list. For more information about Content-Language see RFC 2616 section 14.12.
date¶Gets and sets and deletes the Date header. For more information on Date see RFC 2616 section 14.18. Converts using HTTP date.
Set (add) a cookie for the response
content_length¶Gets and sets and deletes the Content-Length header. For more information on Content-Length see RFC 2616 section 14.17. Converts using int.
www_authenticate¶Gets and sets and deletes the WWW-Authenticate header. For more information on WWW-Authenticate see RFC 2616 section 14.47. Converts using 'parse_auth' and 'serialize_auth'.
charset¶Get/set the charset (in the Content-Type)
headerlist¶The list of response headers.
RequestClass¶Alias for
pyramid.request.Request
Delete a cookie from the client. Note that path and domain must match how the cookie was originally set. This sets the cookie to the empty string, and max_age=0 so that it should expire immediately.
- interface
IIntrospectable[source]¶An introspectable object used for configuration introspection. In addition to the methods below, objects which implement this interface must also implement all the methods of Python's
collections.MutableMapping(the "dictionary interface"), and must be hashable.
register(introspector, action_info)¶Register this IIntrospectable with an introspector. This method is invoked during action execution. Adds the introspectable and its relations to the introspector.
introspectorshould be an object implementing IIntrospector.action_infoshould be a object implementing the interfacepyramid.interfaces.IActionInforepresenting the call that registered this introspectable. Pseudocode for an implementation of this method:def register(self, introspector, action_info): self.action_info = action_info introspector.add(self) for methodname, category_name, discriminator in self._relations: method = getattr(introspector, methodname) method((i.category_name, i.discriminator), (category_name, discriminator))
type_name¶Text type name describing this introspectable
unrelate(category_name, discriminator)¶Indicate an intent to break the relationship between this IIntrospectable with another IIntrospectable (the one associated with the
category_nameanddiscriminator) during action execution.
__hash__()¶Introspectables must be hashable. The typical implementation of an introsepectable's __hash__ is:
return hash((self.category_name,) + (self.discriminator,))
category_name¶introspection category name
title¶Text title describing this introspectable
order¶integer order in which registered with introspector (managed by introspector, usually)
discriminator_hash¶an integer hash of the discriminator
discriminator¶introspectable discriminator (within category) (must be hashable)
relate(category_name, discriminator)¶Indicate an intent to relate this IIntrospectable with another IIntrospectable (the one associated with the
category_nameanddiscriminator) during action execution.
action_info¶An IActionInfo object representing the caller that invoked the creation of this introspectable (usually a sentinel until updated during self.register)
- interface
IIntrospector[source]¶
categories()¶Return a sorted sequence of category names known by this introspector
categorized(sort_key=None)¶Get a sequence of tuples in the form
[(category_name, [{'introspectable':IIntrospectable, 'related':[sequence of related IIntrospectables]}, ...])]representing all known introspectables. Ifsort_keyisNone, each introspectables sequence will be returned in the order the introspectables were added to the introspector. Otherwise, sort_key should be a function that accepts an IIntrospectable and returns a value from it (ala thekeyfunction of Python'ssortedcallable).
add(intr)¶Add the IIntrospectable
intr(use instead ofpyramid.interfaces.IIntrospector.add()when you have a custom IIntrospectable). Replaces any existing introspectable registered using the same category/discriminator.This method is not typically called directly, instead it's called indirectly by
pyramid.interfaces.IIntrospector.register()
get(category_name, discriminator, default=None)¶Get the IIntrospectable related to the category_name and the discriminator (or discriminator hash)
discriminator. If it does not exist in the introspector, return the value ofdefault
get_category(category_name, default=None, sort_key=None)¶Get a sequence of dictionaries in the form
[{'introspectable':IIntrospectable, 'related':[sequence of related IIntrospectables]}, ...]where each introspectable is part of the category associated withcategory_name.If the category named
category_namedoes not exist in the introspector the value passed asdefaultwill be returned.If
sort_keyisNone, the sequence will be returned in the order the introspectables were added to the introspector. Otherwise, sort_key should be a function that accepts an IIntrospectable and returns a value from it (ala thekeyfunction of Python'ssortedcallable).
relate(*pairs)¶Given any number of
(category_name, discriminator)pairs passed as positional arguments, relate the associated introspectables to each other. The introspectable related to each pair must have already been added via.addor.add_intr; aKeyErrorwill result if this is not true. An error will not be raised if any pair has already been associated with another.This method is not typically called directly, instead it's called indirectly by
pyramid.interfaces.IIntrospector.register()
remove(category_name, discriminator)¶Remove the IIntrospectable related to
category_nameanddiscriminatorfrom the introspector, and fix up any relations that the introspectable participates in. This method will not raise an error if an introspectable related to the category name and discriminator does not exist.
Return a sequence of IIntrospectables related to the IIntrospectable
intr. Return the empty sequence if no relations for exist.
unrelate(*pairs)¶Given any number of
(category_name, discriminator)pairs passed as positional arguments, unrelate the associated introspectables from each other. The introspectable related to each pair must have already been added via.addor.add_intr; aKeyErrorwill result if this is not true. An error will not be raised if any pair is not already related to another.This method is not typically called directly, instead it's called indirectly by
pyramid.interfaces.IIntrospector.register()
- interface
IActionInfo[source]¶Class which provides code introspection capability associated with an action. The ParserInfo class used by ZCML implements the same interface.
line¶Starting line number in file (as an integer) of action-invoking code.This will be
Noneif the value could not be determined.
__str__()¶Return a representation of the action information (including source code from file, if possible)
file¶Filename of action-invoking code as a string
- interface
IAssetDescriptor[source]¶Describes an asset.
abspath()¶Returns an absolute path in the filesystem to the asset.
exists()¶Returns True if asset exists, otherwise returns False.
isdir()¶Returns True if the asset is a directory, otherwise returns False.
absspec()¶Returns the absolute asset specification for this asset (e.g.
mypackage:templates/foo.pt).
listdir()¶Returns iterable of filenames of directory contents. Raises an exception if asset is not a directory.
stream()¶Returns an input stream for reading asset contents. Raises an exception if the asset is a directory or does not exist.
- interface
IResourceURL[source]¶
virtual_path¶The virtual url path of the resource as a string.
physical_path_tuple¶The physical url path of the resource as a tuple. (New in 1.5)
virtual_path_tuple¶The virtual url path of the resource as a tuple. (New in 1.5)
physical_path¶The physical url path of the resource as a string.
- interface
ICacheBuster[source]¶A cache buster modifies the URL generation machinery for
static_url(). See Cache Busting.New in version 1.6.
__call__(request, subpath, kw)¶Modifies a subpath and/or keyword arguments from which a static asset URL will be computed during URL generation.
The
subpathargument is a path of/-delimited segments that represent the portion of the asset URL which is used to find the asset. Thekwargument is a dict of keywords that are to be passed eventually tostatic_url()for URL generation. The return value should be a two-tuple of(subpath, kw)wheresubpathis the relative URL from where the file is served andkwis the same input argument. The return value should be modified to include the cache bust token in the generated URL.The
kwdictionary contains extra arguments passed tostatic_url()as well as some extra items that may be usful including:
pathspecis the path specification for the resource to be cache busted.rawspecis the original location of the file, ignoring any calls topyramid.config.Configurator.override_asset().The
pathspecandrawspecvalues are only different in cases where an asset has been mounted into a virtual location usingpyramid.config.Configurator.override_asset(). For example, with a call torequest.static_url('myapp:static/foo.png'), the ``pathspecismyapp:static/foo.pngwhereas therawspecmay bethemepkg:bar.png, assuming a call toconfig.override_asset('myapp:static/foo.png', 'themepkg:bar.png').
- interface
IViewDeriver[source]¶
options¶A list of supported options to be passed to
pyramid.config.Configurator.add_view(). This attribute is optional.
__call__(view, info)¶Derive a new view from the supplied view.
View options, package information and registry are available on
info, an instance ofpyramid.interfaces.IViewDeriverInfo.The
viewis a callable accepting(context, request).
- interface
IViewDeriverInfo[source]¶An object implementing this interface is passed to every view deriver during configuration.
options¶The view options passed to the view, including any default values that were not overriden
settings¶The deployment settings dictionary related to the current application
original_view¶The original view object being wrapped
predicates¶The list of predicates active on the view
package¶The "current package" where the view configuration statement was found
exception_only¶The view will only be invoked for exceptions
registry¶The "current" application registry where the view was created