Skip to content

Instantly share code, notes, and snippets.

@ubergarm
Last active January 5, 2017 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ubergarm/fd5dc92ddc57b62c44378a4db2309a83 to your computer and use it in GitHub Desktop.
Save ubergarm/fd5dc92ddc57b62c44378a4db2309a83 to your computer and use it in GitHub Desktop.
Python 3.5+ Async I/O Web Requests
#!/usr/bin/env python3
## Run
# docker run --rm -it -v `pwd`:/app -w /app python:3.5.2-slim /bin/bash
# pip install aiohttp uvloop
# python async-client.py
## References
# http://aiohttp.readthedocs.io/en/stable/
# https://github.com/MagicStack/uvloop
import aiohttp
import asyncio
import async_timeout
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
async def fetch(session, url):
with async_timeout.timeout(10):
async with session.get(url) as response:
return await response.text()
async def main(loop):
async with aiohttp.ClientSession(loop=loop) as session:
html = await fetch(session, 'http://python.org')
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment