Skip to content

Instantly share code, notes, and snippets.

@arpitbbhayani
Created April 4, 2020 19:42
Show Gist options
  • Save arpitbbhayani/3e71abf7b82f77989ec381ffbeab873d to your computer and use it in GitHub Desktop.
Save arpitbbhayani/3e71abf7b82f77989ec381ffbeab873d to your computer and use it in GitHub Desktop.
def is_allowed(key:str) -> Bool:
"""The function decides is the current request should be served or not.
It accepts the configuration key `key` and checks the number of requests made against it
as per the configuration.
The function returns True if the request goes through and False otherwise.
"""
current_time = int(time.time())
# Fetch the configuration for the given key
# the configuration holds the number of requests allowed in a time window.
config = get_ratelimit_config(key)
# Fetch the current window for the key
# The window returned, holds the number of requests served since the start_time
# provided as the argument.
start_time = current_time - config.time_window_sec
window = get_current_window(key, start_time)
if window.number_of_requests > config.capacity:
return False
# Since the request goes through, register it.
register_request(key, current_time)
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment