Skip to content

Instantly share code, notes, and snippets.

@chandra-prakash-meghwal
Created June 11, 2024 13:22
Show Gist options
  • Save chandra-prakash-meghwal/3694e3a807d622860033f8ba749589a5 to your computer and use it in GitHub Desktop.
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.
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