pyramid - threadlocal在Response的app_iter中无效

0 投票
2 回答
747 浏览
提问于 2025-04-16 19:09

在下面的示例代码中:

from webob import Response
from paste.httpserver import serve


def test_iter():
    from pyramid import threadlocal
    yield 'current request: %s' % threadlocal.get_current_request()


def hello_world(request):
    return Response(app_iter=test_iter())


if __name__ == '__main__':
    from pyramid.config import Configurator
    config = Configurator()
    config.add_view(hello_world)
    app = config.make_wsgi_app()
    serve(app, host='0.0.0.0')

我得到了 当前请求: None。所以,threadlocalapp_iter 里面不管用吗?我有实际的代码需要在视图的几层之外访问 threadlocal,如果每次都要传递 request 变量,那就太麻烦了。

2 个回答

0

可能是个错误吧?

return Response(app_iter=test_iter())

或者

return Response(app_iter=test_iter)
0

根据Pyramid的文档,线程本地的堆栈应该在使用app_iter之后再弹出(参见步骤16和18),不过我在尝试运行你的例子时也遇到了同样的情况。由于文档和实际行为不一致,所以其中一个是错误的,我建议你向Pyramid团队报告一个bug

撰写回答