Context not available when combining decorators and generators #508

Closed
NicolasT opened this Issue May 14, 2012 · 3 comments

Comments

3 participants

In some application I was writing I created a decorator to allow for streaming responses:

def stream(*args, **kwargs):
    def wrapper(f):
        @functools.wraps(f)
        def wrapped(*a, **kw):
            return flask.Response(f(*a, **kw), *args, **kwargs)

        return wrapped

    return wrapper

and another one to JSON'ify the response:

def jsonify(f):
    @stream(
        content_type='application/json',
        headers={
            'Cache-Control': 'no-cache',
        })
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        res = f(*args, **kwargs)

        for chunk in json.JSONEncoder().iterencode(res):
            yield chunk

    return wrapped

Using these on handlers which require access to a context fails though:

RuntimeError: working outside of request context

Full example with some ok and not-ok handers is available at https://gist.github.com/4a443e8214c2c6eea1a5

dAnjou commented Jun 25, 2012

I think, my issue is caused by the same problem. Here is a failing example with full traceback. Mind the comment.

Owner

mitsuhiko commented Jun 27, 2012

That's currently intended behavior. Not sure if we should provide a way to extend the context's lifetime.

Owner

mitsuhiko commented Jun 27, 2012

0.9 now provides a method called stream_with_context that allows you to preserve the context until the request truly ends.

@mitsuhiko mitsuhiko closed this Jun 27, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment