File: example_workers.py

package info (click to toggle)
python-ratelimitqueue 0.2.2-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 180 kB
  • sloc: python: 463; makefile: 15
file content (34 lines) | stat: -rw-r--r-- 735 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
"""Example: Make rate limited API calls in worker threads"""

import ratelimitqueue
import multiprocessing.dummy
import time
import random


def make_call_to_slow_api(url):
    time.sleep(random.uniform(1, 2))
    print("Calling:", url)


LIST_OF_URLS = ["https://example.com/{}".format(i) for i in range(25)]

rlq = ratelimitqueue.RateLimitQueue(calls=3, per=2)
n_workers = 4


def worker(rlq):
    """Makes API calls on URLs from queue until it is empty."""
    while rlq.qsize() > 0:
        url = rlq.get()
        make_call_to_slow_api(url)
        rlq.task_done()


# load up the queue
for url in LIST_OF_URLS:
    rlq.put(url)

# make the calls
with multiprocessing.dummy.Pool(n_workers, worker, (rlq,)) as pool:
    rlq.join()