Skip to content

Instantly share code, notes, and snippets.

@gavinwahl
Created February 1, 2016 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavinwahl/812e6db78bfbf36dcaab to your computer and use it in GitHub Desktop.
Save gavinwahl/812e6db78bfbf36dcaab to your computer and use it in GitHub Desktop.
from django.core.cache import cache
class RateLimiter(object):
def __init__(self, timeout, max_failures):
self.timeout = timeout
self.max_failures = max_failures
def get_key(self, t):
return ':'.join(str(s) for s in t)
def can_submit(self, *args):
return cache.get(self.get_key(args), 0) < self.max_failures
def track_valid_submission(self, *args):
cache.delete(self.get_key(args))
def track_invalid_submission(self, *args):
key = self.get_key(args)
cache.add(key, 0, self.timeout.total_seconds())
cache.incr(key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment