在金字塔中添加在vi之后执行的函数

2024-04-28 13:13:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如何向金字塔应用程序添加在视图中的代码之后执行的代码?在

我需要在视图代码前后对烧杯会话做些什么。在没有问题之前,我使用@subscriber(NewRequest)。到目前为止,我尝试的所有方法似乎都太晚了(我写入会话的值似乎没有被保存,尽管代码是执行的,正如我在日志中看到的)。在

我试着把它放在一个@subscriber(BeforeRender),一个@subscriber(NewResponse),在一个完成的回调中,我添加了NewRequest:event.request.add_finished_callback(finished_callback)-没有我写入会话棒的值。只有我在视图处理程序中添加为最后一行的那一行可以(但我不会在所有视图中写入该行)。在

pyramid docs on NewResponse状态:

Postprocessing a response is usually better handled in a WSGI middleware component than in subscriber code that is called by a pyramid.interfaces.INewResponse event. [...]

但我在这一点上迷路了,因为我对wsgi不太了解,而且试图通过google找到一个可以进入的位置并没有给我指明方向。在


Tags: 方法代码inevent视图pyramid应用程序is
2条回答

从@mikkoohtama的回答中得到了我的解决方案,但是我希望代码出现在这个页面上,所以我做了些解释:

这可以用粗呢来实现。这是一个函数(或其他可调用函数),它被调用而不是视图,并获得调用视图的任务,因此您可以在调用之前和之后执行一些操作。使用这个我也去掉了@subscriber(NewRequest),把它们放在一个地方。想象一下在projects maininit.py中创建wsgi应用程序。项目的名称将是myapp。在

def values_tween_factory(handler, registry):
    """
    Factory for creating the tween that wraps around the view.
    """
    def values_tween(request):
        """
        This is called in stead of the view with the view as param.
        """
        # do stuff before view code with request and session
        request.some_values = request.session.get('stored_values', [])
        # execute the view, creates the response
        response = handler(request)
        # do stuff after the view code with request and session
        request.session['stored_values'] = request.some_values
        # return the response returned by the view
        return response

    # return the new tween
    return state_tween

# [... other module level stuff ...]


def main(global_config, **settings):
    """
    The main function creating the wsgi-app.
    """
    config = Configurator(settings=settings)

    # [...] other stuff, like DB

    # register the tween - must be done by dotted name
    config.add_tween('myapp.values_tween_factory')

    # ... do more other stuff

    application = config.make_wsgi_app()
    # done - return created application object:
    return application

Tweens(between)允许您在每个请求前后执行代码。在

相关问题 更多 >