1

我正在尝试使用异步生成器和 quart 流式传输更大查询的结果。request但是,在使用HTTP 查询的参数时,我陷入了从异步函数中产生的问题

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

4

1 回答 1

0

您将需要使用 stream_with_context 装饰器并返回一个生成器来实现这一点,请参阅这些文档

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()
于 2021-10-21T19:10:03.913 回答