pyramid.events

Functions

subscriber(*ifaces, **predicates)[source]

Decorator activated via a scan which treats the function being decorated as an event subscriber for the set of interfaces passed as *ifaces and the set of predicate terms passed as **predicates to the decorator constructor.

For example:

from pyramid.events import NewRequest
from pyramid.events import subscriber

@subscriber(NewRequest)
def mysubscriber(event):
    event.request.foo = 1

More than one event type can be passed as a constructor argument. The decorated subscriber will be called for each event type.

from pyramid.events import NewRequest, NewResponse
from pyramid.events import subscriber

@subscriber(NewRequest, NewResponse)
def mysubscriber(event):
    print(event)

When the subscriber decorator is used without passing an arguments, the function it decorates is called for every event sent:

from pyramid.events import subscriber

@subscriber()
def mysubscriber(event):
    print(event)

This method will have no effect until a scan is performed against the package or module which contains it, ala:

from pyramid.config import Configurator
config = Configurator()
config.scan('somepackage_containing_subscribers')

Any **predicate arguments will be passed along to pyramid.config.Configurator.add_subscriber(). See Subscriber Predicates for a description of how predicates can narrow the set of circumstances in which a subscriber will be called.

Two additional keyword arguments which will be passed to the venusian attach function are _depth and _category.

_depth is provided for people who wish to reuse this class from another decorator. The default value is 0 and should be specified relative to the subscriber invocation. It will be passed in to the venusian attach function as the depth of the callstack when Venusian checks if the decorator is being used in a class or module context. It's not often used, but it can be useful in this circumstance.

_category sets the decorator category name. It can be useful in combination with the category argument of scan to control which views should be processed.

See the venusian.attach() function in Venusian for more information about the _depth and _category arguments.

Changed in version 1.9.1: Added the _depth and _category arguments.

Event Types

class ApplicationCreated(app)[source]

An instance of this class is emitted as an event when the pyramid.config.Configurator.make_wsgi_app() is called. The instance has an attribute, app, which is an instance of the router that will handle WSGI requests. This class implements the pyramid.interfaces.IApplicationCreated interface.

Note

For backwards compatibility purposes, this class can also be imported as pyramid.events.WSGIApplicationCreatedEvent. This was the name of the event class before Pyramid 1.0.

class NewRequest(request)[source]

An instance of this class is emitted as an event whenever Pyramid begins to process a new request. The event instance has an attribute, request, which is a request object. This event class implements the pyramid.interfaces.INewRequest interface.

class ContextFound(request)[source]

An instance of this class is emitted as an event after the Pyramid router finds a context object (after it performs traversal) but before any view code is executed. The instance has an attribute, request, which is the request object generated by Pyramid.

Notably, the request object will have an attribute named context, which is the context that will be provided to the view which will eventually be called, as well as other attributes attached by context-finding code.

This class implements the pyramid.interfaces.IContextFound interface.

Note

As of Pyramid 1.0, for backwards compatibility purposes, this event may also be imported as pyramid.events.AfterTraversal.

class BeforeTraversal(request)[source]

An instance of this class is emitted as an event after the Pyramid router has attempted to find a route object but before any traversal or view code is executed. The instance has an attribute, request, which is the request object generated by Pyramid.

Notably, the request object may have an attribute named matched_route, which is the matched route if found. If no route matched, this attribute is not available.

This class implements the pyramid.interfaces.IBeforeTraversal interface.

class NewResponse(request, response)[source]

An instance of this class is emitted as an event whenever any Pyramid view or exception view returns a response.

The instance has two attributes:request, which is the request which caused the response, and response, which is the response object returned by a view or renderer.

If the response was generated by an exception view, the request will have an attribute named exception, which is the exception object which caused the exception view to be executed. If the response was generated by a 'normal' view, this attribute of the request will be None.

This event will not be generated if a response cannot be created due to an exception that is not caught by an exception view (no response is created under this circumstace).

This class implements the pyramid.interfaces.INewResponse interface.

Note

Postprocessing a response is usually better handled in a WSGI middleware component than in subscriber code that is called by a pyramid.interfaces.INewResponse event. The pyramid.interfaces.INewResponse event exists almost purely for symmetry with the pyramid.interfaces.INewRequest event.

class BeforeRender(system, rendering_val=None)[source]

Subscribers to this event may introspect and modify the set of renderer globals before they are passed to a renderer. This event object itself has a dictionary-like interface that can be used for this purpose. For example:

from pyramid.events import subscriber
from pyramid.events import BeforeRender

@subscriber(BeforeRender)
def add_global(event):
    event['mykey'] = 'foo'

An object of this type is sent as an event just before a renderer is invoked.

If a subscriber adds a key via __setitem__ that already exists in the renderer globals dictionary, it will overwrite the older value there. This can be problematic because event subscribers to the BeforeRender event do not possess any relative ordering. For maximum interoperability with other third-party subscribers, if you write an event subscriber meant to be used as a BeforeRender subscriber, your subscriber code will need to ensure no value already exists in the renderer globals dictionary before setting an overriding value (which can be done using .get or __contains__ of the event object).

The dictionary returned from the view is accessible through the rendering_val attribute of a BeforeRender event.

Suppose you return {'mykey': 'somevalue', 'mykey2': 'somevalue2'} from your view callable, like so:

from pyramid.view import view_config

@view_config(renderer='some_renderer')
def myview(request):
    return {'mykey': 'somevalue', 'mykey2': 'somevalue2'}

rendering_val can be used to access these values from the BeforeRender object:

from pyramid.events import subscriber
from pyramid.events import BeforeRender

@subscriber(BeforeRender)
def read_return(event):
    # {'mykey': 'somevalue'} is returned from the view
    print(event.rendering_val['mykey'])

In other words, rendering_val is the (non-system) value returned by a view or passed to render* as value. This feature is new in Pyramid 1.2.

For a description of the values present in the renderer globals dictionary, see System Values Used During Rendering.

update(E, **F)

Update D from dict/iterable E and F. If E has a .keys() method, does: for k in E: D[k] = E[k] If E lacks .keys() method, does: for (k, v) in E: D[k] = v. In either case, this is followed by: for k in F: D[k] = F[k].

clear() None.  Remove all items from D.
copy() a shallow copy of D
fromkeys(value=None, /)

Create a new dictionary with keys from iterable and values set to value.

get(key, default=None, /)

Return the value for key if key is in the dictionary, else default.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
pop(k[, d]) v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault(key, default=None, /)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

values() an object providing a view on D's values

See Using Events for more information about how to register code which subscribes to these events.