在金字塔中,是否有任何类型的" hook"这是在调用视图之前发生的?

时间:2017-01-23 17:17:26

标签: hook pyramid

我想在调用任何/所有视图之前执行一些代码,例如一些日志记录。

金字塔中有没有办法做到这一点?

2 个答案:

答案 0 :(得分:3)

补间[1]和视图派生[2]文档都有定时代码示例。这取决于您想要测量的内容以及您在进行测量时希望获得的信息。例如,补间不知道执行了哪个视图,只知道URL。但它包含更多的管道。

[1] http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/hooks.html#creating-a-tween

[2] http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/hooks.html#custom-view-derivers

答案 1 :(得分:2)

你可以通过订阅一些活动来做到这一点。

http://docs.pylonsproject.org/projects/pyramid/en/latest/api/events.html

您想要的可能是ContextFound

您可以使用装饰器(http://docs.pylonsproject.org/projects/pyramid/en/latest/api/events.html#pyramid.events.subscriber)订阅:

from pyramid.events import ContextFound
from pyramid.events import subscriber

@subscriber(ContextFound)
def do_something(event):
    print(event)
    print(event.request)

或迫切需要add_subscriberhttp://docs.pylonsproject.org/projects/pyramid/en/latest/api/config.html#pyramid.config.Configurator.add_subscriber):

from pyramid.events import ContextFound

def main(global_config, **settings):
    # rest of your config here
    config.add_subscriber(do_something, ContextFound)

def do_something(event):
    print(event)
    print(event.request)