2017-08-01 68 views
0

我向服務器發出POST請求以生成CSV文件,並且POST請求的響應是我要寫入文件的CSV數據。Python請求 - 下載進度條

我永遠不知道CSV文件的大小(它可以是10MB,100MB或1000MB),因此沒有內容長度標題。

我寫了一個函數,用於下載向服務器發出POST請求,生成CSV文件並將響應寫入CSV文件。但是,我正在努力進步吧。

如何添加進度條?

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

看一看:進度條,而下載文件 - 過度HTTP與 - 請求(https://stackoverflow.com/questions/37573483/progress-bar- while-download-file-over-http-with-requests),或者:[python-progress-bar-and-downloads](https://stackoverflow.com/questions/15644964/python-progress-bar-and-downloads ) –

+0

我看過那些,但無法計算如何添加進度條在我的情況下,因爲我的響應頭將不會有內容長度頭。 – user6037143

回答

0
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