【问题标题】:Add function in pyramid that executes after view在金字塔中添加视图后执行的功能
【发布时间】:2016-04-15 04:42:33
【问题描述】:

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

我需要在查看代码之前和之后对我的烧杯会话做一些事情。之前没问题,我用的是@subscriber(NewRequest)。到目前为止,我尝试的所有方法似乎都发生得太晚了(我写入会话的值似乎没有被保存,尽管代码已执行,正如我在日志中看到的那样)。

我尝试将其放入@subscriber(BeforeRender)@subscriber(NewResponse),并在完成的回调中添加NewRequestevent.request.add_finished_callback(finished_callback)——我没有写入会话中的任何值。只有我作为视图处理程序中最后一行添加的那一行(但我不会在我的所有视图中都写那一行)。

pyramid docs on NewResponse 状态:

在 WSGI 中间件组件中处理响应的后处理通常比在由 pyramid.interfaces.INewResponse 事件调用的订阅者代码中处理得更好。 [...]

但我对此感到迷茫,因为我不太了解 wsgi,并且试图通过谷歌找到一个进入的地点并没有指向我的任何地方。

【问题讨论】:

  • 刚刚发现 BeforeRender 确实有效 - 如果呈现某些内容,则重定向不是这种情况。

标签: python session pyramid wsgi


【解决方案1】:

Tweens (be-tween) 允许您在每个请求之前和之后执行代码。

【讨论】:

  • 这完美地解决了我的问题 - 我用我所做的添加了一个答案,所以代码就在 SO 中。
【解决方案2】:

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

这可以通过补间来实现。那是一个函数(或其他可调用的),它被调用而不是视图并获得调用视图的工作,因此您可以在调用之前和之后做一些事情。使用它,我也摆脱了@subscriber(NewRequest) 并将其全部放在一个地方。想象一下,在您的项目主 init.py 中创建 wsgi-app。该项目的名称将是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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-18
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2017-03-16
    • 1970-01-01
    相关资源
    最近更新 更多