Last active
May 5, 2017 07:58
-
-
Save vkobel/b85fd274590d790e51b71b6e7779e52f to your computer and use it in GitHub Desktop.
Async http get using aiohttp
This file contains hidden or 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
import aiohttp | |
import asyncio | |
def async_http_get(urls, extractor=None, json_response=True): | |
tasks = [] | |
sem = asyncio.Semaphore(32) | |
async def fetch(session, url): | |
async with session.get(url) as response: | |
if json_response: | |
response = await response.json() | |
if extractor: | |
response = extractor(response) | |
else: | |
response = await response.text() | |
return (url, response) | |
async def sem_fetch(sem, session, url): | |
async with sem: | |
return await fetch(session, url) | |
async def run(loop, sem): | |
async with aiohttp.ClientSession(loop=loop) as session: | |
for url in urls: | |
task = asyncio.ensure_future(sem_fetch(sem, session, url)) | |
tasks.append(task) | |
return await asyncio.gather(*tasks) | |
loop = asyncio.get_event_loop() | |
return loop.run_until_complete(run(loop, sem)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment