yinmin
2023-05-09 23:51:52 +08:00
如果并发量不大的话,可以直接 ajax 使用 stream 流,log 信息通过 yield 返回
服务器端代码:
from django.http import StreamingHttpResponse
import time
def stream_response(request):
def data():
for i in range(10):
time.sleep(1)
try:
yield f"data: {i}\n\n"
except GeneratorExit:
# 在这里执行清理操作,例如关闭数据库连接或释放其他资源
print("Client closed the connection.")
raise
response = StreamingHttpResponse(data())
response['Content-Type'] = 'text/event-stream'
return response
浏览器端 javascript 代码:
//调用上面这段服务器 stream_response ,日志显示在 data_container 的<div>里,stop_btn 是一个 button 按钮
var source = new EventSource("{% url 'stream_response' %}");
var container = document.getElementById('data_container');
source.onmessage = function(event) {
container.innerHTML += event.data + "<br>";
};
var stop_btn = document.getElementById('stop_btn');
stop_btn.onclick = function() {
source.close();
};
大致思路如上,代码没仔细调试过,你自己具体研究。