在较早的问题中,其中一位作者aiohttp
提出了使用 aiohttp 获取多个 url 的好方法,该方法使用来自以下的新async with
语法Python 3.5
:
import aiohttp
import asyncio
async def fetch(session, url):
with aiohttp.Timeout(10):
async with session.get(url) as response:
return await response.text()
async def fetch_all(session, urls, loop):
results = await asyncio.wait([loop.create_task(fetch(session, url))
for url in urls])
return results
if __name__ == '__main__':
loop = asyncio.get_event_loop()
# breaks because of the first url
urls = ['http://SDFKHSKHGKLHSKLJHGSDFKSJH.com',
'http://google.com',
'http://twitter.com']
with aiohttp.ClientSession(loop=loop) as session:
the_results = loop.run_until_complete(
fetch_all(session, urls, loop))
# do something with the the_results
但是,当其中一个session.get(url)
请求中断时(如上所述,因为http://SDFKHSKHGKLHSKLJHGSDFKSJH.com
),错误不会被处理并且整个事情都会中断。
我寻找插入有关结果的测试的方法session.get(url)
,例如寻找 atry ... except ...
或 a 的位置,if response.status != 200:
但我只是不了解如何使用async with
以及await
各种对象。
由于async with
还很新,所以例子不多。如果一个asyncio
向导可以展示如何做到这一点,这对许多人来说将是非常有帮助的。毕竟,大多数人想要测试的第一件事asyncio
就是同时获取多个资源。
目标
目标是我们可以检查the_results
并快速查看:
- 此 url 失败(以及原因:状态代码,可能是异常名称),或
- 这个网址有效,这是一个有用的响应对象