Home > Net >  Setting API rate limit on Python with ratelimit library
Setting API rate limit on Python with ratelimit library

Time:02-04

 from ratelimit import limits, RateLimitException, sleep_and_retry
 from backoff import on_exception, expo
 max_hit = 5
 period = 300
 @limits(calls=max_hit, period=period)
    def StashNotes(self):
         url = ("https://www.r10.net/")
         raw_data = requests.get(url, headers=headers)
         if raw_data.status_code != 200:
              raise Exception('API response: {}'.format(raw_data.status_code))
         else:
                ## some unnecessary things here ##

I am trying to limit the API rate with a max hit of 5 and period 300, so my requests.get will not hit any more than 5 times in 300 second period. @limits(calls=max_hit,period=period) doesn't work, and can't really figure out why.

Is there any other way to do this besides ratelimit library, or how to fix @limits decoration? Any kind of solution is appreciated, thanks.

headers=headers contains sensitive information but it doesn't matter anyway just 2 cookie values in it.

CodePudding user response:

It throughs exception for me while I try to make more than 5 iterations of call on API, getting exception after 5 calls,

ratelimit.exception.RateLimitException: too many calls

Fullcode:

from flask import Flask
from ratelimit import limits

max_hit = 5
period = 300

@limits(calls=max_hit, period=period)
def StashNotes():
    return "sany"

app = Flask(__name__)

@app.route("/")
def hello_world():
    return StashNotes()
  •  Tags:  
  • Related