2017-01-23 21 views
1

我想在执行任何/所有视图之前执行一些代码,例如某些日志记录。在金字塔中,是否有任何一种“钩子”发生在视图被调用之前?

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

+1

我已经看过查看Derivers,但你必须让他们对视图基础视图,它违背了自动登录的消息每次当我的目的视图被调用,而不必修改视图.. –

+0

不正确。视图派生器包装所有视图。他们分别包装每个视图,允许他们接受每个视图选项,甚至避免包装特定的视图,但这取决于他们的身体。 –

回答

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) 
相关问题