Server Sent events with Flask and Google App Engine

情到浓时终转凉″ 提交于 2020-07-08 00:46:10

问题


I've been trying to get a webapp to work which uses Server-Sent Events. The app that I've written works on my local machine when using Flask's app.run() method. But when I run it on GAE, I've not been able to make it work.

The webapp uses SSE to publish a message with the current time every so often. The client simply adds it to the HTML of a div.

Flask app

import random

from datetime import datetime
from flask import render_template, Response
from time import sleep

from message_server import app

def event_stream():
    while True:
        time_now = datetime.now()
        message = "New message at time: {0}".format(time_now.strftime("%H:%M:%S"))
        yield "event: {0}\ndata: {1}\n\n".format("listen", message)
        sleep(random.randint(1, 5))


@app.route('/')
def hello():
    return render_template('home.html')


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

Javascript in home.html

var source = new EventSource("/stream");
source.onmessage = function(event) {
  document.getElementById("messages").innerHTML += event.data + "<br>";
};

source.addEventListener("listen", function(event) {
  document.getElementById("messages").innerHTML += event.data + "<br>";
}, false);

GAE app.yaml

runtime: python
env: flex

entrypoint: gunicorn -b :$PORT --worker-class gevent --threads 10 message_server:app

runtime_config:
    python_version: 3

manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10

My directory structure is as following:

app.yaml
/message_server
    __init__.py
    sse.py
    /templates
        home.html

message_server is the package that contains the flask app object.

I am using Firefox 67 to test my app.

  • In the networking tab of Firefox developer console, I see a GET request made to /stream, but no response received even after a minute.
  • In the GAE logs, I am seeing "GET /stream" 499.

How do I figure out what's wrong?


回答1:


I found the answer while browsing Google App Engine's documentation - on this page: https://cloud.google.com/appengine/docs/flexible/python/how-requests-are-handled

Essentially, you want the following header in the HTTP response for SSE to work:

X-Accel-Buffering: no

This disables buffering that is enabled by default. I tested it and SSE is working as expected for me.



来源:https://stackoverflow.com/questions/56644367/server-sent-events-with-flask-and-google-app-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!