Python异步/等待下载URL列表

Yi *_*hou 7 python asynchronous python-asyncio aiohttp

我正在尝试从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()
Run Code Online (Sandbox Code Playgroud)

如果我删除try部分错误消息:

回溯(最近一次调用最后一次):
文件"test.py",第111行,在
x.download_queue(urls)
文件"test.py",第99行,在download_queue中
循环.run_until_complete(asyncio.gather(*tasks))
文件"/home/yz/miniconda3/lib/python3.6/asyncio/base_events.py",第467行,在run_until_complete中
返回future.result()
文件"test.py",第73行,在解压缩
数据中= await self.download_file (session,queue_url)
文件"test.py",第65行,在download_file中
返回{"error":remotefile.status,"data":""}
文件"/home/yz/miniconda3/lib/python3.6/site - packages/async_timeout/init .py",第46行,退出时
引发asyncio.TimeoutError from None
concurrent.futures._base.TimeoutError

Mik*_*mov 8

tasks = [asyncio.ensure_future(self.unzip(session, q)) for _ in range(len(urls))]
loop.run_until_complete(asyncio.gather(*tasks))
Run Code Online (Sandbox Code Playgroud)

在这里,您开始同时下载所有网址的过程.这意味着你也开始计算所有这些的超时.一旦它是一个很大的数字,例如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):
Run Code Online (Sandbox Code Playgroud)


Vin*_*ent 5

作为@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
Run Code Online (Sandbox Code Playgroud)

这是使用管道的等效实现:

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))
Run Code Online (Sandbox Code Playgroud)

您可以使用以下协程对其进行测试:

async def fetch(session, url):
    await asyncio.sleep(random.random())
    return url

async def process(data):
    print(data)
Run Code Online (Sandbox Code Playgroud)

在此演示文档中查看更多 aiostream 示例。

免责声明:我是项目维护者。