如何在流式下载期间准确预测计算进度

how to predict accurately calculate progress during streaming download

我正在尝试使用流式 post 请求从我的在线数据库下载文件,同时提供相对下载进度的准确指示以驱动我的 QT 应用程序中的进度条。

我想我可以简单地比较 chunk_size * chunk 与文件大小的数量,以了解我下载了多少相关数据,但它似乎不是那样工作的。 为了测试我对块的理解,我将 chunk_size 设置为与文件大小相同(大约 9.8MB)。这是我的测试代码:

with closing(requests.post(ipAddress,
                           headers={'host':hostURL},
                           data=dataDict,
                           timeout=timeout,
                           stream=True)) as responseObject:
    chunkNumber = 0
    for chunk in responseObject.iter_content(chunk_size=10276044):
        print chunkNumber
        chunkNumber += 1
        content += chunk

我原以为只会看到一两个块,但当我多次 运行 测试时,我看到 chunkNumber 增加到 1600 到 4000 以上。

我显然误解了 chunk_size 的用法,所以我的问题是: 如何在 iter_content() 循环期间准确确定下载的相对进度,以便将进度条从 0 驱动到 100%?

干杯, 坦率

我为自己的项目找到的解决方案是找到响应的 长度并除以 100

这是 Python 3 代码,因此只需 删除打印语句中的括号 即可与 2.

兼容
f = open(title, 'wb')
response = requests.get(url, params=query, headers=HDR, stream=True)
size = int(response.headers.get('content-length'))
CHUNK = size//100 # size for a percentage point
if CHUNK > 1000000: # place chunk cap on >1MB files
    CHUNK = 100000 # 0.1MB
print(size, 'bytes')
print("Writing to file in chunks of {} bytes...".format(CHUNK))
actual = 0 # current progress
try:
    for chunk in response.iter_content(chunk_size=CHUNK):
        if not chunk: break
        f.write(chunk)
        actual += len(chunk) # move progress bar
        percent = int((actual/size)*100)
        if 'idlelib' in sys.modules: # you can take these conditions out if you don't have windows
        #if you do then import sys, os at the start of the program
            if not(percent % 5):
                print('{}%'.format(percent), end=' ')
        else:
            os.system('title {}% {}/{}'.format(percent, actual, size))
except Exception as e:
    print(e)
finally:
    f.close()