的獲取對於aiohttp入門文檔給下面的客戶端的例子:「異步與」在Python 3.4
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,請使用@coroutine裝飾器替換await和 async def。
如果我按照這些指示,我得到:
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)
然而,這將無法運行,因爲async with
沒有在Python 3.4的支持:
$ python3 client.py
File "client.py", line 7
async with session.get(url) as response:
^
SyntaxError: invalid syntax
如何翻譯的async with
語句與Python 3.4一起工作?
謝謝你指點我那些例子。我沒有找到那些。 – Imran
請注意,如果發生異常,您通常要*關閉*響應。 –
@MartijnPieters謝謝,你是對的。我修復了代碼以匹配'_RequestContextManager .__ aexit__'邏輯。 –