在前面的问题中,《aiohttp
》的一位作者好心地建议使用Python 3.5
中新的async with
语法:
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)
的测试结果,例如寻找try ... except ...
或if response.status != 200:
的位置,但我不知道如何处理async with
、await
和各种对象.
由于async with
仍然是非常新的,所以没有太多的例子.如果一个asyncio
向导能演示如何做到这一点,对很多人都会很有帮助.毕竟,大多数人想用asyncio
测试的第一件事就是同时获得多个资源.
Goal
我们的目标是,我们可以判断the_results
个,并很快看到:
- 此url失败(以及原因:状态代码,可能是异常名称),或
- 这个url有效,下面是一个有用的响应对象