<p>从@mikkoohtama的回答中得到了我的解决方案,但是我希望代码出现在这个页面上,所以我做了些解释:</p>
<p>这可以用粗呢来实现。这是一个函数(或其他可调用函数),它被调用而不是视图,并获得调用视图的任务,因此您可以在调用之前和之后执行一些操作。使用这个我也去掉了<code>@subscriber(NewRequest)</code>,把它们放在一个地方。想象一下在projects main<strong>init</strong>.py中创建wsgi应用程序。项目的名称将是<code>myapp</code>。在</p>
<pre><code>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
</code></pre>