throttle¶
Events rate limiting.
This module provides Throttle, an object which limits the rate at which events - like external API calls - are triggered, by delaying the events which exceed a given per-second limit.
Throttle
¶
A rate limiter.
A Throttle ensures that trigger() calls are spaced by at least the period corresponding to the configured events-per-second limit, blocking the caller - if needed - until the next event can be triggered.
The object is thread-safe: the events spacing is computed over the trigger() calls made by all the threads.
Example
throttle = throttle.Throttle(2) # at most 2 events per second
with throttle.trigger():
pass # perform_event() here - spaced by >= 0.5s from the previous one
Source code in py_misc_utils/throttle.py
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |
trigger()
¶
Triggers an event, delaying it if the rate limit would be exceeded.
Blocks the calling thread until the event can be triggered without exceeding the configured events-per-second limit.
Returns:
| Type | Description |
|---|---|
|
The throttle lock, held for the duration of the event - allowing |
|
|
callers to serialize the triggered events. |
Source code in py_misc_utils/throttle.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |