【发布时间】:2018-12-20 15:41:26
【问题描述】:
我正在尝试通过设置 stream=True
从 python 请求库下载大文件但我希望这个函数异步执行,并将响应发送回服务器并在后台下载。
这是我的代码
async def downloadFile(url, filename):
r = requests.get(url, stream=True)
with open(os.path.join('./files', filename), 'wb+') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
# Creating same file name
# with _done appended to know that file has been downloaded
with open(os.path.join('./files', filename + '_done'), 'w+') as f:
f.close()
await asyncio.sleep(1)
像这样从其他函数调用这个函数
# check if file exist in server
if(os.path.exists(os.path.join('./files', fileName))):
#file exist!!!
#check if done file exist
if(os.path.exists(os.path.join('./files', fileName + '_done'))):
#done file exist
self.redirect(self.request.protocol + "://" +
self.request.host + '/files/' + fileName)
else:
#done file not exist. Wait for 5 min more
self.write('Wait 5 min')
self.finish()
else:
# file doesnt exist. Initiate download
self.write('Wait 5 min')
self.finish()
d = asyncio.ensure_future(downloadFile(
fileRes, fileName))
# loop = asyncio.get_event_loop()
# loop.run_until_complete(d)
问题是文件已创建,但其大小仍为 0,并且从未创建附加“_done”的文件。 我在这里做错了什么?
【问题讨论】:
-
您的代码对我有用。也许enable debugging for requests?
-
你的代码也适合我
-
此代码仅适用于第一次。如果我立即发起请求,它会等待整个文件下载。我已经用有关如何调用下载功能的详细信息更新了我的问题。请检查。
标签: python python-3.x python-requests python-asyncio