The Getting Started docs for aiohttp give the following client example:
```import asyncio
import aiohttp
async def fetch_page(session, url):
with aiohttp.Timeout(10):
async with session.get(url) as response:
assert response.status == 200
return await response.read()
loop = asyncio.get_event_loop()
with aiohttp.ClientSession(loop=loop) as session:
content = loop.run_until_complete(
fetch_page(session, 'http://python.org'))
print(content)
他们针对Python 3.4用户给出以下说明:
如果您正在使用Python 3.4,请将await替换为yield from,将async def替换为@coroutine装饰器。
如果我按照这些说明操作,我会得到:
import aiohttp
import asyncio
@asyncio.coroutine
def fetch(session, url):
with aiohttp.Timeout(10):
async with session.get(url) as response:
return (yield from response.text())
if __name__ == '__main__':
loop = asyncio.get_event_loop()
with aiohttp.ClientSession(loop=loop) as session:
html = loop.run_until_complete(
fetch(session, 'http://python.org'))
print(html)
不过,这段代码无法运行,因为Python 3.4不支持async with
语法:
$ python3 client.py
File "client.py", line 7
async with session.get(url) as response:
^
SyntaxError: invalid syntax
我该如何翻译async with
语句,以便与Python 3.4一起使用?