问题
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