Python Pyramid 简明教程

Python Pyramid - Events

Pyramid 应用程序在它的生命周期中发出多种事件。虽然这些事件通常不需要被使用完,通过适当处理这些事件可以执行稍微高级的操作。

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.

Pyramid 框架广播的事件仅在您用某个订阅者函数注册这个事件时才开始有用。必须将发出的事件用作 subscriber 函数的参数。

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 −

在下面的代码段中,应用程序配置为订阅者函数在发出 NewRequest 对象时由该函数调用。

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)

还有一个 @subscriber() 装饰器用于配置事件。

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

与装饰视图配置一样,在这里也必须执行 config.scan() 才能使装饰器生效。

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

正如前面提到的,Pyramid 应用程序发出多种类型的事件。这些事件类可用于 pyramid.event 模块内。它们如下所示 −

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 −

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

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

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

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

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

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