Skip to content

Instantly share code, notes, and snippets.

@betafcc
Last active September 7, 2018 16:07
Show Gist options
  • Save betafcc/cb77737b34216d3cdd0c85b8acef2313 to your computer and use it in GitHub Desktop.
Save betafcc/cb77737b34216d3cdd0c85b8acef2313 to your computer and use it in GitHub Desktop.
import asyncio
from random import randint
async def get(url):
# simula a demora na request
await asyncio.sleep(1)
# simula uma resposta duma realistica função 'get'
return bool(randint(0, 1))
async def call_api(url):
response = await get(url)
if not response:
return await call_api(url)
return response
host = 'https://minha.api/'
request_paths = [
'pokemon/1',
'digimon/2',
'pokemon/2',
'digimon/3',
'pokemon/5',
]
# note aqui, eu faço um gerador de corotines para cada url
requests = (call_api(host + path) for path in request_paths)
# a parte 'asyncio.gather(*requests)' cria uma nova coroutine, do qual o resultado
# vai ser uma lista com o resultado de cada uma das resquests
gathered_requests = asyncio.gather(*requests)
# por fim, executa
results = asyncio.get_event_loop().run_until_complete(gathered_requests)
print(results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment