Created
June 11, 2024 13:22
-
-
Save chandra-prakash-meghwal/3694e3a807d622860033f8ba749589a5 to your computer and use it in GitHub Desktop.
Decorator that prevents a function from being called more than the request limit every time period.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from datetime import datetime, timedelta | |
from functools import wraps | |
class throttle(object): | |
""" | |
Decorator that prevents a function from being called more than the request limit every | |
time period. | |
To create a function that cannot be called more than 10 ten time in a minute: | |
@throttle(requests_limit=10, minutes=1) | |
def my_fun(): | |
pass | |
""" | |
def __init__(self, requests_limit=10, seconds=0, minutes=0, hours=0): | |
self.throttle_period = timedelta( | |
seconds=seconds, minutes=minutes, hours=hours | |
) | |
self.time_of_last_call = datetime.min | |
self.requests_limit = requests_limit | |
def __call__(self, fn): | |
@wraps(fn) | |
def wrapper(*args, **kwargs): | |
now = datetime.now() | |
time_since_last_call = now - self.time_of_last_call | |
if time_since_last_call > self.throttle_period: | |
self.requests_limit = 0 | |
if self.requests_limit < 10: | |
self.time_of_last_call = now | |
self.requests_count += 1 | |
return fn(*args, **kwargs) | |
else: | |
return {"message": "LIMIT REACHED", "statusCode": 429} | |
return wrapper | |
@throttle(requests_limit=10, seconds=30) | |
def lambda_handler(event, context): | |
return { | |
'statusCode': 200, | |
'body': json.dumps('Hello from Lambda!') | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment