librelist archives

« back to archive

Request context when passing a generator to Response()

Request context when passing a generator to Response()

From:
Joe Shaw
Date:
2012-11-05 @ 20:17
Hi,

I'd like to use a generator function to return data in a response in
chunks, but the functions called from that generator require a request
context because they use url_for().

The code is roughly structured like so:

@app.route("/")
def index():
    return Response(serialize_stuff(), direct_passthrough=True)

def serialize_stuff():
    yield "Hello"
    yield url_for("world")
    yield "Goodbye"

By the time the url_for() is called, the request context is long gone.
 Passing in the app and request objects and trying to construct a new
request context doesn't seem to work.  Any ideas?

Thanks,
Joe

Re: Request context when passing a generator to Response()

From:
Joe Shaw
Date:
2012-11-05 @ 20:28
Hi again,

On Mon, Nov 5, 2012 at 3:17 PM, Joe Shaw <joe@joeshaw.org> wrote:
> I'd like to use a generator function to return data in a response in
> chunks, but the functions called from that generator require a request
> context because they use url_for().
> [...]
> By the time the url_for() is called, the request context is long gone.
>  Passing in the app and request objects and trying to construct a new
> request context doesn't seem to work.  Any ideas?

... and of course I found the answer 10 minutes after sending to the
mailing list, like a true rookie.

http://flask.pocoo.org/docs/patterns/streaming/#streaming-with-context

New in 0.9 you can wrap the generator in a stream_with_context() and
have the request context available inside the generator.

Joe