"Assíncrono com" no Python 3.4
Os documentos de introdução ao aiohttp fornecem o seguinte exemplo de cliente:
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)
E eles dão a seguinte nota para usuários do Python 3.4:
Se você estiver usando o Python 3.4, substitua aguardar com yield de e async def por um decorador de @coroutine.
Se eu seguir estas instruções, recebo:
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)
No entanto, isso não será executado, porqueasync with
não é suportado no Python 3.4:
$ python3 client.py
File "client.py", line 7
async with session.get(url) as response:
^
SyntaxError: invalid syntax
Como posso traduzir oasync with
para trabalhar com o Python 3.4?