【问题标题】:Server Sent events with Flask and Google App Engine服务器使用 Flask 和 Google App Engine 发送事件
【发布时间】:2019-10-31 19:38:00
【问题描述】:

我一直在尝试让一个使用服务器发送事件的 web 应用程序工作。当使用 Flask 的 app.run() 方法时,我编写的应用程序可以在我的本地机器上运行。但是当我在 GAE 上运行它时,我无法让它工作。

webapp 使用 SSE 每隔一段时间发布一条带有当前时间的消息。客户端只需将其添加到 div 的 HTML 中。

烧瓶应用

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")

home.html 中的 JavaScript

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

我的目录结构如下:

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

message_server 是包含烧瓶app 对象的包。

我正在使用 Firefox 67 测试我的应用。

  • 在 Firefox 开发者控制台的网络选项卡中,我看到向 /stream 发出的 GET 请求,但即使过了一分钟也没有收到响应。
  • 在 GAE 日志中,我看到了 "GET /stream" 499

如何找出问题所在?

【问题讨论】:

  • 能否请您澄清一下您的代码中的 message_server 到底是什么,我可以看到您在 app.yaml 和 Flask 应用程序文件中都使用了它。
  • @dhauptman 在上述问题的末尾添加了更多信息。感谢您查看此内容!

标签: google-app-engine flask gunicorn wsgi server-sent-events


【解决方案1】:

我在浏览 Google App Engine 的文档时找到了答案 - 在此页面上:https://cloud.google.com/appengine/docs/flexible/python/how-requests-are-handled

基本上,您希望 HTTP 响应中的以下标头以使 SSE 正常工作:

X-Accel-Buffering: no

这会禁用默认启用的缓冲。我对其进行了测试,SSE 按我的预期工作。

【讨论】:

  • 它对我不起作用。是在标准环境还是灵活环境中?
  • X-Accel-Buffering 不再出现在链接页面上。
猜你喜欢
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多