首页 > 解决方案 > 实时从 django 获取数据到 React

问题描述

我创建了一个 API,它使用 python 请求库从 jenkins 下载工件。API 由 react 前端触发。我想在反应前端显示下载进度。

        download_folder = "location"
        bytes_read = 0
        url = 'https://jenkinsServer/job/'+ ID + '/' + Build_no + '/artifact/*zip*/archive.zip'
        response = requests.get(url, auth=(username, APIPin), stream=True, allow_redirects=True, verify = False)

        with open(download_folder, 'wb') as f:
            itrcount=1
            for chunk in response.iter_content(chunk_size=1024):
                itrcount=itrcount+1
                f.write(chunk)
                bytes_read += len(chunk)
                print(bytes_read)
        response.close()

上面是 Django 内部的视图。我想将 bytes_read 值获取到前端反应以将其用于进度条。在反应中,我只是使用了 fetch

  var url = "DJANGO API URL FOR THE ABOVE CODE;
  fetch(url)
  .then(res => res.json())
  .then()
  .catch((error) =>{ console.log('Error');
  })

我发现了一些可以在 Django 中用于发送实时数据的通道,但不太了解。我是 Django 和 React 的初学者,因此请不要介意代码/任何错误。我只需要在前端显示 python 请求的下载进度。或者如果我可以使用任何其他方法?

标签: pythondjangoreactjspython-requestsprogress-bar

解决方案


推荐阅读