我有一种下载XML文件的方法。我想显示一个下载进度栏and that's why I use clint。问题是,此文件的大小可能在〜1kb到〜700mb之间。
def download_file(self, dest:str, filename:str):
r = requests.get(self.url, stream=True, headers={
"Accept": "application/xml",
"Accept-Charset": "utf-8",
"Accept-Encoding": None,
"Accept-Language": "pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4",
"Authorization": self.auth
})
with open(f"{dest}/{filename}", 'wb') as f:
total_length = int(r.headers.get("content-length"))
for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
# f.flush()
return filename
此代码在一段时间后返回以下错误:
int() argument must be a string, a bytes-like object or a number, not 'NoneType'
因为r.headers.get("content-length")
返回None,它应该返回文件的大小,这是一个问题,因为它必须一直不间断地永久下载237849234文件(出于调试目的,我希望进度条)。无论如何,如果文件下载了好一会儿但没有返回内容长度,怎么办?
编辑:
我已经实现了一些逻辑来保持下载的进行,但是仍然令人沮丧,因为无法知道文件的大小。
with open(f"{dest}/{filename}", 'wb') as f:
total_length = r.headers.get("content-length")
if not total_length:
f.write(r.content)
else:
for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(int(total_length)/1024) + 1):
if chunk: # filter out keep-alive new chunks
f.write(chunk)