【问题标题】:Python-requests - Download progress barPython-requests - 下载进度条
【发布时间】:2018-01-08 09:49:56
【问题描述】:

我向服务器发出 POST 请求以生成 CSV 文件,POST 请求的响应是我要写入文件的 CSV 数据。

我永远无法知道 CSV 文件的大小(可以是 10MB、100MB 或 1000MB),因此没有内容长度标头。

我编写了一个函数,下载向服务器发出 POST 请求,生成 CSV 文件并将响应写入 CSV 文件。但是,我在进度条上苦苦挣扎。

如何添加进度条?

r = requests.post(URL, data, stream=True)
#Download progress here

【问题讨论】:

标签: python-requests


【解决方案1】:
def download_file(url, local_path="./"):
    local_filename = url.split('/')[-1]
    path = local_path + local_filename

    r = requests.get(url, stream=True)
    total_size = int(r.headers.get('content-length', 0))

    with open(local_filename, 'wb') as f:
        for chunk in tqdm(r.iter_content(32*1024), total=total_size,unit='B', unit_scale=True):
            if chunk:
                f.write(chunk)

    return path

【讨论】:

  • 您还应该使用unit_divisor=1024 - 否则它将显示 Mebibyte 而不是 MB(但仍注释为 MB)。
猜你喜欢
  • 2013-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多