File: example_throttlers_aiohttp.py

package info (click to toggle)
python-throttler 1.2.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 180 kB
  • sloc: python: 473; makefile: 4; sh: 2
file content (41 lines) | stat: -rw-r--r-- 1,063 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import asyncio
import time

import aiohttp

from throttler import Throttler, ThrottlerSimultaneous


class SomeAPI:
    api_url = 'https://example.com'

    def __init__(self, throttler):
        self.throttler = throttler

    async def request(self, session: aiohttp.ClientSession):
        async with self.throttler:
            async with session.get(self.api_url) as resp:
                return resp

    async def many_requests(self, count: int):
        async with aiohttp.ClientSession() as session:
            coros = [self.request(session) for _ in range(count)]
            for coro in asyncio.as_completed(coros):
                response = await coro
                print(f'{int(time.time())} | Result: {response.status}')


def example():
    async def run():
        api = SomeAPI(Throttler(rate_limit=3, period=1.0))
        await api.many_requests(100)

    asyncio.run(run())


def example_simultaneous():
    async def run():
        api = SomeAPI(ThrottlerSimultaneous(count=5))
        await api.many_requests(100)

    asyncio.run(run())