如何使用DJango在Web浏览器中显示rsync --progress?

Joy*_*ind 5 python django rsync

我正在编写一个Python/Django应用程序,它使用rsync协议将文件从服务器传输到本地机器.我们将处理大文件,因此进度条是必需的.命令中的--progress参数rsync做得很漂亮.所有细节进展都显示在终端中.如何在Web浏览器中显示进度?有没有钩功能或类似的东西?或者我可以将进度存储在日志文件中,调用它并每隔一分钟左右更新一次吗?

Cal*_*eng 5

基本原则是在子进程中运行rsync,公开Web API并通过javascript获取更新

这是一个例子.

import subprocess
import re
import sys

print('Dry run:')
cmd = 'rsync -az --stats --dry-run ' + sys.argv[1] + ' ' + sys.argv[2]
proc = subprocess.Popen(cmd,
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,)

remainder = proc.communicate()[0]
mn = re.findall(r'Number of files: (\d+)', remainder)
total_files = int(mn[0])
print('Number of files: ' + str(total_files))

print('Real rsync:')
cmd = 'rsync -avz  --progress ' + sys.argv[1] + ' ' + sys.argv[2]
proc = subprocess.Popen(cmd,
                        shell=True,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,)

while True:
             output = proc.stdout.readline()
if 'to-check' in output:
             m = re.findall(r'to-check=(\d+)/(\d+)', output)
             progress = (100 * (int(m[0][1]) - int(m[0][0]))) / total_files
             sys.stdout.write('\rDone: ' + str(progress) + '%')
             sys.stdout.flush()
             if int(m[0][0]) == 0:
                      break

print('\rFinished')
Run Code Online (Sandbox Code Playgroud)

但这只能告诉我们标准输出(stdout)的进展情况.

但是,我们可以修改此代码以将进度作为JSON输出返回,并且可以通过progress webservice/API我们创建的输出使此输出可用.

在客户端使用,我们将编写javascript(ajax)来progress webservice/API不时联系我们,并使用该信息更新客户端的东西,例如文本消息,图像的宽度,某些div的颜色等