2

I am trying to use async generator and quart to stream the result of bigger queries. However I am stuck in yielding from an async function while using the request argument of the HTTP query

from quart import request, Quart
app = Quart(__name__)

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

Start with hypercorn module:app and calling it with curl localhost:8000/?arg=monkey results in

[...]
  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

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Bigbohne
  • 1,356
  • 3
  • 12
  • 24
  • Changing the `yield` to a `return` works perfectly ... but not what I intended – Bigbohne Jun 15 '21 at 14:54
  • 1
    Your function isn't an async generator — does it work if you change it from `def function():` to `async def function():`? – L3viathan Jun 15 '21 at 15:40
  • @L3viathan I made a mistake in my example, sry. I talked to the maintainer over on https://gitter.im/python-quart/lobby. From his perspective it looks like a bug – Bigbohne Jun 15 '21 at 18:27

1 Answers1

1

You will need to use the stream_with_context decorator and return a generator to achieve this, see these 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()
pgjones
  • 6,044
  • 1
  • 14
  • 12