Ratelimit components
Project description
cs.ratelimit
This provides a threadsafe configurable rate limiter to a Python callable.
It's easy to create a rate limited function
>>> from datetime import datetime, timedelta
>>> from cs import ratelimit
>>> @ratelimit.ratelimited(max_count=1, interval=timedelta(seconds=1), block=False)
... def my_func():
... pass
>>> my_func()
>>> try:
... my_func()
... except ratelimit.RateLimitExceeded:
... print(u"Too fast!")
Too fast!
We can just as easily make it a blocking rate limiter
>>> @ratelimit.ratelimited(max_count=1, interval=timedelta(seconds=1), block=True)
... def my_func():
... pass
>>> my_func()
>>> my_func() # blocks, doesn't raise
It's also easy to create a class-level rate limited method
>>> class MyClass1:
... @ratelimit.ratelimitedmethod(max_count=1, interval=timedelta(seconds=1), block=False)
... def my_method(self):
... pass
>>> instance1 = MyClass1()
>>> instance2 = MyClass1()
>>> instance1.my_method()
>>> try:
... instance2.my_method()
... except ratelimit.RateLimitExceeded:
... print(u"Too fast!")
Too fast!
A more advanced use case is per-instance limiters
>>> from operator import attrgetter
>>> class MyClass2:
... def __init__(self):
... self.rl = ratelimit.RateLimitProperties(max_count=1,
... interval=timedelta(seconds=1),
... block=False)
... @ratelimit.ratelimitedmethod(attrgetter('rl'))
... def my_method(self):
... pass
>>> instance1 = MyClass2()
>>> instance2 = MyClass2()
The rate limiters in these instances are independent
>>> instance1.my_method()
>>> instance2.my_method()
>>> try:
... instance1.my_method()
... except ratelimit.RateLimitExceeded:
... print(u"Too fast!")
Too fast!
They can also be updated at any time
>>> with instance2.rl.rlock: #needed in threaded environments
... instance2.rl.max_count = 2
>>> instance2.my_method()
WE STOP BREACHES
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
cs.ratelimit-1.3.0.tar.gz
(17.7 kB
view hashes)
Built Distribution
Close
Hashes for cs.ratelimit-1.3.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 98f35d66dfaa293dd47cfbc91b0c216f756144d7b2e9e2c2b09ab054bcdf465a |
|
MD5 | 0cedc230ff97f61776397515d1804ebc |
|
BLAKE2b-256 | 3cfcf0d1085363b933b097a8ebeaf548cc09eafff00f3a0d6042bddc86ff2fa7 |