Skip to main content
 首页 » 编程设计

python之如何使用 Ajax 从 Django 流式传输写入标准输出的 Fabric 任务结果

2024年10月25日32findumars

我有一个从 Django 执行的长时间运行的 Fabric 任务(~30 分钟)。

示例代码在这里:

from django.http import HttpResponse 
from fabric.tasks import execute 
from fabric.api import sudo 
 
@task 
def runcmd(): 
    result = sudo('ls -l') 
 
 
def executer(request): 
    result = execute( 
        runcmd, 
        hosts=['localhost'] 
    ) 
    return HttpResponse(result['localhost']) 

这里的问题我不想等 30 分钟才能显示日志 (stdout)。我可以在任务完成后得到结果。我只需要在任务运行时捕获标准输出并将其发送给客户端。

我尝试了 StreamingHttpResponse 和 ajax,但没有成功。

我该如何解决这个问题,或者有什么替代方案吗?

问候,

请您参考如下方法:

您可以使用您自己的版本包装 Fabric 函数 run/sudo 并在那里覆盖它们的标准输出。

Docs says:

To override which local streams are used to display remote stdout and/or stderr, specify stdout or stderr. (By default, the regular sys.stdout and sys.stderr Python stream objects are used.)

然后,您可以将一个 StringIO(内存中的类文件对象)实例传递给 stdout 参数。观察 StringIO 实例中的新行,当新行到达时,您可以yield 将其发送给 StreamingHttpResponse(参见 this answer 示例)。