我已经使用 Flask 框架开发并成功测试了一个简单的 SSE Python 应用程序。使用 Flask 服务器时,每条 SSE 消息都会按应有的方式实时显示。当我尝试在 IIS 下运行完全相同的内容时,输出被阻止并且仅以类似长轮询的方式显示;仅当 SSE 连接终止时。即使使用 Localhost 也会发生这种情况,所以我认为这不是由代理或防火墙引起的。
这是 Python 代码:
'''
Test SSE with Python and Flask
'''
import flask, flask.views
import time
app = flask.Flask(__name__)
app.secret_key = "anything"
def event_stream():
mylist = (x for x in range(10))
for i in mylist:
if i < 10:
message = "Message # %s" % i
yield 'data: %s\n\n' % message
time.sleep(1)
yield 'data: // END\n\n'
return
@app.route('/stream')
def stream():
Msg = event_stream()
return flask.Response(Msg,
mimetype="text/event-stream")
class View(flask.views.MethodView):
def get(self):
return flask.render_template('ssetest.html')
def post(self):
return self.get()
app.add_url_rule('/', view_func=View.as_view('main'), methods = ["GET", "POST"])
if __name__ == '__main__':
app.run()
下面是 Jinja 模板 ssetest.html:
<!doctype html>
<html>
<head>
<title> Test SSE </title>
</head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<style>body { max-width: 1000px; margin: 100; padding: 1em; background: black; color: #fff; font: 16px/1.6 menlo, monospace; }</style>
<body>
<form action = "/" method = "post">
<input type = "submit" value = "Execute Again" />
</form>
<pre id="out"></pre>
<script>
var out = document.getElementById('out');
var color = 'yellow'
function sse() {
var url = '/stream';
document.write('STARTING');
var source = new EventSource(url);
source.onmessage = function(e) {
var line = '<p style="line-height: 0.1;color:'+color+'">'+e.data+'</p>';
out.innerHTML = line + out.innerHTML;
var start_msg = e.data.substring(0,2);
if (start_msg == '//')
{
source.close();
}
};
}
sse();
</script>
</body>
</html>