Last active
January 5, 2017 20:59
-
-
Save ubergarm/fd5dc92ddc57b62c44378a4db2309a83 to your computer and use it in GitHub Desktop.
Python 3.5+ Async I/O Web Requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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