I personally do use aiohttp, sanic, asyncio, aiomysql, ... and I really enjoy it. It's a huge difference in performance. Was doing some benchmarks for my Slack Applications / bots and the difference was noticeable, even by the end users. (Mostly prototypes / MVPs, reason for experimenting with sanic).
Anyway, here's an example. You can learn how to fire & wait for one request and how to fire & wait for many of them.
NOTE: No error handling & coindesk has rate limiting. Run this two, three times and then you have to wait.
import asyncio
import aiohttp
async def get_currencies(session):
async with session.get('https://api.coindesk.com/v1/bpi/supported-currencies.json') as response:
result = await response.json(content_type='text/html')
return {x['currency']: x['country'] for x in result}
async def bitcoin_price(session, currency):
async with session.get(f'https://api.coindesk.com/v1/bpi/currentprice/{currency}.json') as response:
result = await response.json(content_type='application/javascript')
return result['bpi'][currency]
async def bitcoin_prices():
async with aiohttp.ClientSession() as session:
# Get list of available currencies
currencies = await get_currencies(session)
# Prepare tasks for all currencies
tasks = [
asyncio.ensure_future(bitcoin_price(session, currency))
for currency in currencies.keys()
]
# Fire them and wait for results
await asyncio.gather(*tasks)
results = [x.result() for x in tasks]
# Print them
for x in results:
print(' - {0} {1:12.1f} {2}'.format(x['code'], x['rate_float'], x['description']))
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(bitcoin_prices())
if __name__ == '__main__':
main()