sforyou
Junior Member
Em đang tìm hiểu Python, các bác giúp em lỗi này với ạ.
Em muốn truyền qua SSE mỗi từ của câu message, mỗi từ cách nhau 1s.
Nhưng khi chạy, em thấy các data bị chờ nhau, phải sau đúng 5s mới thấy các data hiển thị 1 phát duy nhất.
data: Tôi
data: đang
data: tìm
data: hiểu
data: Python
Đáng lẽ phải hiển thị lần lượt cách nhau 1s mới đúng ý em. Không biết lỗi chỗ nào ạ. Em cảm ơn!
app.py như sau:
Trang html: em tạo
EventSource với onmessage để lấy phản hồi từ nguồn stream:
Em muốn truyền qua SSE mỗi từ của câu message, mỗi từ cách nhau 1s.
Nhưng khi chạy, em thấy các data bị chờ nhau, phải sau đúng 5s mới thấy các data hiển thị 1 phát duy nhất.
data: Tôi
data: đang
data: tìm
data: hiểu
data: Python
Đáng lẽ phải hiển thị lần lượt cách nhau 1s mới đúng ý em. Không biết lỗi chỗ nào ạ. Em cảm ơn!
app.py như sau:
Python:
from flask import Flask, request, Response
import time
app = Flask(__name__, template_folder='')
def event_stream(texts):
for word in texts:
time.sleep(1)
yield "data: {}\n\n".format(word + " ")
yield "data: {}\n\n".format("endresponse")
@app.route("/stream", methods=['GET'])
def stream_route():
message = "Tôi đang tìm hiểu Python"
words = message.split()
return response(event_stream(words), mimetype='text/event-stream')
if __name__ == "__main__":
app.run()
Trang html: em tạo
EventSource với onmessage để lấy phản hồi từ nguồn stream:
JavaScript:
var source = new EventSource("/python_app/stream"); Nơi chứa app.py
source.onmessage = function(event) {
var data = JSON.parse(event.data);
$("#output").append(event.data);
};