1

I am trying to use Flask to send a stream of events to a front-end client as documented in this question. This works fine if I don't access anything in the request context, but fails as soon as I do.

Here's an example to demonstrate.

from time import sleep
from flask import Flask, request, Response

app = Flask(__name__)

@app.route('/events')
def events():
    return Response(_events(), mimetype="text/event-stream")

def _events():
    while True:
        # yield "Test"  # Works fine
        yield request.args[0]  # Throws RuntimeError: Working outside of request context
        sleep(1)

Is there a way to access the request context for server-sent events?

1 Answer 1

2

You can use the @copy_current_request_context decorator to make a copy of the request context that your event stream function can use:

from time import sleep
from flask import Flask, request, Response, copy_current_request_context

app = Flask(__name__)

@app.route('/events')
def events():
    @copy_current_request_context
    def _events():
        while True:
            # yield "Test"  # Works fine
            yield request.args[0]
            sleep(1)

    return Response(_events(), mimetype="text/event-stream")

Note that to be able to use this decorator the target function must be moved inside the view function that has the source request.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.