Kris Harper
Kris Harper

Reputation: 5862

How can I send server-side events from Flask while accessing the request context?

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?

Upvotes: 1

Views: 1511

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67507

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.

Upvotes: 2

Related Questions