ratelimit icon indicating copy to clipboard operation
ratelimit copied to clipboard

How to impose two rate limits?

Open dizhu1991 opened this issue 8 years ago • 6 comments

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.

dizhu1991 avatar Jan 15 '18 22:01 dizhu1991

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

3lixy avatar Feb 22 '18 08:02 3lixy

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.

rokcarl avatar Jul 12 '18 10:07 rokcarl

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 avatar Nov 20 '18 20:11 ckuethe

@ckuethe Hi. Can ypu explain ypur code a little bit, particularly the chained decorators?

abhi-jha avatar Dec 20 '19 03:12 abhi-jha

@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

ckuethe avatar Dec 20 '19 04:12 ckuethe

Thanks.

abhi-jha avatar Dec 20 '19 10:12 abhi-jha