不能在 quart 处理程序中使用 request 和 yield

Cannot use request and yield in quart handler

我正在尝试使用异步生成器和 quart 来流式传输更大查询的结果。但是,在使用 HTTP 查询

request 参数时,我陷入了从异步函数中产生的困境
from quart import request, Quart
app = Quart(__name__)

@app.route('/')
async def function():
    arg = request.args.get('arg')
    yield 'HelloWorld'

hypercorn module:app 开始并用 curl localhost:8000/?arg=monkey 调用它会导致

[...]
  File "/usr/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/andre/src/cid-venv/lib/python3.8/site-packages/quart/utils.py", line 88, in _inner
    return next(iterable)
  File "/home/andre/src/cid/mve.py", line 7, in function
    arg = request.args.get('arg')
  File "/home/andre/src/cid-venv/lib/python3.8/site-packages/werkzeug/local.py", line 422, in __get__
    obj = instance._get_current_object()
  File "/home/andre/src/cid-venv/lib/python3.8/site-packages/werkzeug/local.py", line 544, in _get_current_object
    return self.__local()  # type: ignore
  File "/home/andre/src/cid-venv/lib/python3.8/site-packages/quart/globals.py", line 26, in _ctx_lookup
    raise RuntimeError(f"Attempt to access {name} outside of a relevant context")
RuntimeError: Attempt to access request outside of a relevant context

您将需要使用 stream_with_context 装饰器和 return 生成器来实现此目的,请参阅这些 docs

from quart import request, stream_with_context, Quart

app = Quart(__name__)

@app.route('/')
async def function():
    @stream_with_context
    async def _gen():
        arg = request.args.get('arg')
        yield 'HelloWorld'
    return _gen()