我正在尝试从FTP服务器下载超过30,000个文件,并且在使用异步IO进行一些谷歌搜索之后似乎是一个好主意。但是,下面的代码无法下载任何文件并返回超时错误。我真的很感激任何帮助!谢谢!
class pdb:
def __init__(self):
self.ids = []
self.dl_id = []
self.err_id = []
async def download_file(self, session, url):
try:
with async_timeout.timeout(10):
async with session.get(url) as remotefile:
if remotefile.status == 200:
data = await remotefile.read()
return {"error": "", "data": data}
else:
return {"error": remotefile.status, "data": ""}
except Exception as e:
return {"error": e, "data": ""}
async def unzip(self, session, work_queue):
while not work_queue.empty():
queue_url = await work_queue.get()
print(queue_url)
data = await self.download_file(session, queue_url)
id = queue_url[-11:-7]
ID = id.upper()
if not data["error"]:
saved_pdb = os.path.join("./pdb", ID, f'{ID}.pdb')
if ID not in self.dl_id:
self.dl_id.append(ID)
with open(f"{id}.ent.gz", 'wb') as f:
f.write(data["data"].read())
with gzip.open(f"{id}.ent.gz", "rb") as inFile, open(saved_pdb, "wb") as outFile:
shutil.copyfileobj(inFile, outFile)
os.remove(f"{id}.ent.gz")
else:
self.err_id.append(ID)
def download_queue(self, urls):
loop = asyncio.get_event_loop()
q = asyncio.Queue(loop=loop)
[q.put_nowait(url) for url in urls]
con = aiohttp.TCPConnector(limit=10)
with aiohttp.ClientSession(loop=loop, connector=con) as session:
tasks = [asyncio.ensure_future(self.unzip(session, q)) for _ in range(len(urls))]
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
如果我删除try
部分错误消息:
追踪(最近的呼叫最后):
文件“test.py”,第111行,中 x.download_queue(URL)的
在download_queue中文件“test.py”,第99行 loop.run_until_complete(asyncio.gather(*任务))
在run_until_complete中输入文件“/home/yz/miniconda3/lib/python3.6/asyncio/base_events.py”,第467行 返回future.result()
文件“test.py”,第73行,解压缩 data = await self.download_file(session,queue_url)
在download_file中文件“test.py”,第65行 return {“error”:remotefile.status,“data”:“”}
在退出中输入文件“/home/yz/miniconda3/lib/python3.6/site- packages / async_timeout / init .py”,第46行 从无提升asyncio.TimeoutError concurrent.futures._base.TimeoutError
答案 0 :(得分:5)
tasks = [asyncio.ensure_future(self.unzip(session, q)) for _ in range(len(urls))]
loop.run_until_complete(asyncio.gather(*tasks))
在这里,您开始同时下载所有网址的过程。这意味着你也开始计算所有这些的超时。一旦它是30,000这样的大数字,由于网络/ ram / cpu容量,它在10秒内无法完成。
为避免这种情况,您应该保证协同程序的限制同时启动。通常可以使用像asyncio.Semaphore这样的同步原语来实现这一点。
它看起来像这样:
sem = asyncio.Semaphore(10)
# ...
async def download_file(self, session, url):
try:
async with sem: # Don't start next download until 10 other currently running
with async_timeout.timeout(10):
答案 1 :(得分:1)
作为@ MikhailGerasimov的信号量方法的替代方法,您可以考虑使用aiostream.stream.map运算符:
from aiostream import stream, pipe
async def main(urls):
async with aiohttp.ClientSession() as session:
ws = stream.repeat(session)
xs = stream.zip(ws, stream.iterate(urls))
ys = stream.starmap(xs, fetch, ordered=False, task_limit=10)
zs = stream.map(ys, process)
await zs
这是使用管道的等效实现:
async def main3(urls):
async with aiohttp.ClientSession() as session:
await (stream.repeat(session)
| pipe.zip(stream.iterate(urls))
| pipe.starmap(fetch, ordered=False, task_limit=10)
| pipe.map(process))
您可以使用以下协程进行测试:
async def fetch(session, url):
await asyncio.sleep(random.random())
return url
async def process(data):
print(data)
在此demonstration和documentation中查看更多aiostream示例。
免责声明:我是项目维护者。