How to impose two rate limits?
Hi @tomasbasham , I am very grateful for this package as it solved my headache. I'm writing Python code that calls Strava API, and it's working now thanks to rate_limit!
Strava API has two rate limits: 600 per 15min and 30,000 per day. How do I impose these two simultaneously?
Thanks.
Perhaps you could use a function inside a function kind of like a wrapper?
I have not tested the below it is just an idea that might work.
from ratelimit import rate_limited
import requests
FIFTEEN_MINUTES = 15*60
ONE_DAY = 3600*24
@rate_limited(30000, ONE_DAY)
def wrapper_api_call(self, url):
@rate_limited(600, FIFTEEN_MINUTES)
def call_api(self, url):
response = requests.get(url)
if response.status_code != 200:
raise ApiError('Cannot call API: {}'.format(response.status_code))
return response
Worst case you can just be slower than the daily limit. So in your case you can do 30,000 per day, which is 1,250 per hour which is 312.5 per 15 minutes.
So if you set your limit at 300 per 15 minutes, you'll surely be in the green.
This seems to work.
from ratelimit import limits, sleep_and_retry
import datetime
@sleep_and_retry
@limits(5, 1)
@sleep_and_retry
@limits(15, 60)
def foo():
print "foo() at {}".format(datetime.datetime.now())
def main():
while True:
foo()
if __name__ == '__main__':
main()
@ckuethe Hi. Can ypu explain ypur code a little bit, particularly the chained decorators?
@ckuethe Hi. Can ypu explain ypur code a little bit, particularly the chained decorators?
Just a little demo that implements dual rate limits... 15 requests in 60 seconds, with no more than 5 requests in any one second
Thanks.