4 ms·
Sync, using requests: import requests def main(): with requests.Session() as s: r = s.get('https://...') result = r.json() main()
by gabrielsroka 5y ago
Sync, using requests:
import requests
def main():
with requests.Session() as s:
r = s.get('https://...')
result = r.json()
main()
Async, using aiohttp:
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as s:
async with s.get('https://...') as r:
result = await r.json()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
If you're making many HTTP requests, you can use async, queue them up and it greatly improves performance.
See also
https://docs.aiohttp.org/en/stable/http_request_lifecycle.html https://docs.aiohttp.org/en/stable/http_request_lifecycle.ht...
- gabrielsroka 5y agoHere are some more realistic examples utilizing the official HN API. The async version is about 30 times faster than the sync version when you set the total to a high number, the maximum is about 500. Performance tables are in the code itself. https://github.com/gabrielsroka/hn https://github.com/gabrielsroka/hn See also https://news.ycombinator.com/item?id=30172433 https://news.ycombinator.com/item?id=30172433