Created
October 14, 2019 13:19
-
-
Save sinwoobang/6128290f6eea0cb259ee600b25e1e03d to your computer and use it in GitHub Desktop.
How to give an interval between requests on aiohttp
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
import time | |
from typing import List | |
import aiohttp | |
import asyncio | |
from asyncio.futures import Future | |
URL = 'https://www.mocky.io/v2/5185415ba171ea3a00704eed' # Mock API | |
TIME_INTERVAL = 1 # 1 second | |
LOCK = asyncio.Lock() | |
async def _request(session: aiohttp.ClientSession) -> None: | |
await LOCK.acquire() | |
start_time = time.time() | |
await session.get(URL, ssl=False) | |
end_time = time.time() | |
elapsed_time = end_time - start_time | |
if elapsed_time < TIME_INTERVAL: | |
print('WAITING ..') | |
await asyncio.sleep(TIME_INTERVAL - elapsed_time) | |
LOCK.release() | |
async def request(cnt) -> List[Future]: | |
tasks: List[Future] = [] | |
async with aiohttp.ClientSession() as session: | |
for i in range(cnt): | |
task: Future = asyncio.ensure_future(_request(session=session)) | |
tasks.append(task) | |
await asyncio.gather(*tasks) | |
return tasks | |
if __name__ == '__main__': | |
loop = asyncio.get_event_loop() | |
futures = asyncio.ensure_future(request(cnt=10)) | |
loop.run_until_complete(futures) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment