用 django 调用长时间执行的脚本,如何返还输出呢?

359 天前
 mylifcc

我想用 django 做一个接口,接到 start 请求后,就执行一个 python 脚本,同时可以将输出或日志返还给前端,接到 stop 请求就 kill 脚本,这样如何写比较合理呢? 用 celery 写了一下,但是无法结束进程,不知道原因,也搞不定日志。。。

1651 次点击
所在节点    Django
5 条回复
baoyinhe
359 天前
输出存 redis 或数据库,kill 脚本可以看一下这个 base64 aHR0cHM6Ly9qdWVqaW4uY24vcG9zdC83MTE5Njc4MjQ0ODU2NjkyNzcz
Lucups
359 天前
建议使用 websocket

或者考虑一下 xterm.js
37Y37
359 天前
yinmin
359 天前
如果并发量不大的话,可以直接 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();
};

大致思路如上,代码没仔细调试过,你自己具体研究。
noparking188
358 天前
supervisor 呢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/938676

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX