在 Pyramid 中,是否有任何类型的 "hook" 发生在视图被调用之前?
In Pyramid, is there any kind of "hook" that occurs just before a view is called?
我有一些代码想在调用 any/all 视图之前执行,例如一些日志记录。
有没有办法在金字塔中做到这一点?
您可以通过订阅一些活动来做到这一点。
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_subscriber
(http://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)
tween [1] 和 view deriver [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
我有一些代码想在调用 any/all 视图之前执行,例如一些日志记录。
有没有办法在金字塔中做到这一点?
您可以通过订阅一些活动来做到这一点。
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_subscriber
(http://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)
tween [1] 和 view deriver [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