2
我正在創建將處理數據的Web應用程序,所以我在Flask中使用了Server Sent Event。會話對象在Flask中不起作用stream_with_context函數
我需要將會話變量存儲在SSE函數中,但燒瓶不會在函數外面看到它。我能以某種方式修復它嗎?
MWE:
server.py:
from flask import Flask, render_template, session, Response, stream_with_context
import time
app = Flask(__name__)
app.secret_key = b'132d2dcf59f9604c0b48e4e3a1a1cd19a0abf121b48a4777'
@app.route('/')
def get_page():
return render_template('progress.html')
@app.route('/progress')
def progress():
def generate():
x = 0
while x < 100:
x = x + 10
print(x)
time.sleep(0.2)
yield "data:" + str(x) + "\n\n"
session['result'] = x
print(session['result']) #100
return Response(stream_with_context(generate()), mimetype= 'text/event-stream')
@app.route('/done')
def done():
print(session['result']) #KeyError: 'result'
return session['result']
if __name__ == '__main__':
app.run(debug=True)
progress.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script>
var source = new EventSource("/progress");
source.onmessage = function(event) {
$('.progress-bar').css('width', event.data+'%').attr('aria-valuenow', event.data);
if (event.data >=100) {
source.close();
window.location = "http://127.0.0.1:5000/done"
}
}
</script>
</head>
<body>
<div class="progress" style="width: 50%; margin: 50px;">
<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
</div>
</div>
</body>
</html>
好的,謝謝,我現在明白這一點。我應該將結果'x'傳遞給JS,並將此結果作爲url參數重定向到'/ done?result = x'並將其存儲在會話中的'done()'函數中?或者有更好的方法來做到這一點? – sweetSTEAM