ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 2761

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

49.2. OTHER INTERFACES

from repoze.events import subscriber

from pyramid.interfaces import IBeforeRender

@subscriber(IBeforeRender) def add_global(event):

event[’mykey’] = ’foo’

See also Using The Before Render Event.

rendering_val

The value returned by a view or passed to a render method for this rendering. This feature is new in Pyramid 1.2.

49.2 Other Interfaces

interface IAuthenticationPolicy

An object representing a Pyramid authentication policy.

remember(request, principal, **kw)

Return a set of headers suitable for ‘remembering’ the principal named principal when 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 None if 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 return

None.

unauthenticated_userid(request)

Return the unauthenticated userid. This method performs the same duty as authenticated_userid but 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.

effective_principals(request)

Return a sequence representing the effective principals including the userid and any groups belonged to by the current user, including ‘system’ groups such as Everyone and Authenticated.

589


49. PYRAMID.INTERFACES

forget(request)

Return a set of headers suitable for ‘forgetting’ the current user on subsequent requests.

interface IAuthorizationPolicy

An object representing a Pyramid authorization policy.

principals_allowed_by_permission(context, permission)

Return a set of principal identifiers allowed by the permission in context. This behavior is optional; if you choose to not implement it you should define this method as something which raises a NotImplementedError. This method will only be called when the pyramid.security.principals_allowed_by_permission API is used.

permits(context, principals, permission)

Return True if any of the principals is allowed the permission in the current context, else return False

interface IExceptionResponse

 

 

 

 

 

 

Extends:

 

 

 

pyramid.interfaces.IException,

pyramid.interfaces.IResponse

 

 

 

 

An interface representing a WSGI

response which is also an exception ob-

ject.

Register

an exception view

using this interface as a context to

apply the registered view for all

exception types raised by Pyramid inter-

nally (any exception that inherits from pyramid.response.Response,

including

pyramid.httpexceptions.HTTPNotFound

and

pyramid.httpexceptions.HTTPForbidden).

 

 

 

prepare(environ)

 

 

 

 

 

 

Prepares the response for being called as a WSGI application

 

 

interface IRoute

 

 

 

 

 

 

 

Interface

representing

the

type

of

object

returned

from

IRoutesMapper.get_route

name

The route name

pattern

The route pattern

590


49.2. OTHER INTERFACES

factory

The root factory used by the Pyramid router when this route matches (or None)

generate(kw)

Generate a URL based on filling in the dynamic segment markers in the pattern using the kw dictionary provided.

pregenerator

This attribute should either be None or a callable object implementing the

IRoutePregenerator interface

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.

match(path)

If the path passed to this function can be matched by the pattern of 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 provided path.

If the path passed to this function cannot be matched by the pattern of this route, return None.

interface IRoutePregenerator

__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 by route_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, kw

591

49. PYRAMID.INTERFACES

You can employ a pregenerator by passing a pregenerator argument to the pyramid.config.Configurator.add_route() function.

interface ISession

Extends: pyramid.interfaces.IDict

An interface representing a session (a web session object, usually accessed via request.session.

Keys and values of a session must be pickleable.

invalidate()

Invalidate the session. The action caused by invalidate is implementationdependent, 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.

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 optional queue, which must be a string. If allow_duplicate is false, if the msg already exists in the queue, it will not be readded.

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 does session[’foo’] = {}, changed() needn’t be called. However, if subsequently he or she does session[’foo’][’a’] = 1, changed() must be called for the sessioning machinery to notice the mutation of the internal dictionary.

get_csrf_token()

Return a random cross-site request forgery protection token. It will be a string. If a token was previously added to the session via new_csrf_token, that token will be returned. If no CSRF token was previously set into the session, new_csrf_token will be called, which will create and set a token, and this token will be returned.

592


49.2. OTHER INTERFACES

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()

new_csrf_token()

Create and set into the session a new, random cross-site request forgery protection token. Return the token. It will be a string.

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()

interface ISessionFactory

An interface representing a factory which accepts a request object and returns an ISession object

__call__(request)

Return an ISession object

interface IRendererInfo

An object implementing this interface is passed to every renderer factory constructor as its only argument (conventionally named info)

name

The value passed by the user as the renderer name

package

The “current package” when the renderer configuration statement was found

settings

The deployment settings dictionary related to the current application

registry

The “current” application registry when the renderer was created

type

The renderer type name

593


49. PYRAMID.INTERFACES

interface ITemplateRenderer

Extends: pyramid.interfaces.IRenderer

implementation()

Return the object that the underlying templating system uses to render the template; it is typically a callable that accepts arbitrary keyword arguments and returns a string or unicode object

interface IViewMapperFactory

__call__(self, **kw)

Return an object which implements pyramid.interfaces.IViewMapper.

kw

will

be a

dictionary

containing view-specific arguments,

such

as

permission,

predicates,

attr,

renderer,

and

other

items.

An

IViewMapperFactory

is used by

pyramid.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

__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 by pyramid.interfaces.IViewMapperFactory.

interface IDict

__delitem__(k)

Delete an item from the dictionary which is passed to the renderer as the renderer globals dictionary.

setdefault(k, default=None)

Return the existing value for key k in the dictionary. If no value with k exists in the dictionary, set the default value 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

__getitem__(k)

Return the value for key k from the dictionary or raise a KeyError if the key doesn’t exist

594