Python Pyramid - Events



A Pyramid application emits various events during the course of its lifetime. Although these events need not be used up normally, slightly advanced operations can be performed by properly handling these events.

An event broadcast by the Pyramid framework becomes usable only when you register it with a subscriber function. The emitted event must be used as the argument of the subscriber function.

def mysubscriber(event):
   print("new request")

However, a subscriber function becomes operational only when it is added to the application's configuration with the help of add_subscriber() method as shown below −

In the following snippet, the application is configured so that the subscriber function is invoked when it emits NewRequest object.

from pyramid.events import NewRequest
config.add_subscriber(mysubscriber, NewRequest)

There is also a @subscriber() decorator for configuring the event.

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

@subscriber(NewRequest)
def mysubscriber(event):
   print ("new request")

As with the decortive view configuration, here also the config.scan() must be performed for the decorator to be effective.

As mentioned earlier, the Pyramid application emits a variety of event types. These event classes are available in pyramid.event module. They are listed below −

  • ApplicationCreated − This event is transmitted just when the config.make_wsgi_app() method of the Configurator class is called to return the WSGI application object.

  • NewRequest − An object of this event class is emitted every time the Pyramid application starts processing an incoming request. This object has a request attribute which is the request object as supplied by WSGI environ dictionary.

  • ContextFound − The application's router traverses all the routes and finds an appropriate match with the URL pattern. This is when the object of ContextFound class is instantiated.

  • BeforeTraversal − 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.

  • NewResponse − As the name suggests, this event is raised whenever any Pyramid view callable returns a response. This object has request and response attributes.

  • BeforeRender − An object of this type is transmitted as an event just before a renderer is invoked. The subscriber function to this event has access to the application's global data (which is in the form of a dict object) and can modify value of one or more keys.

Advertisements