Created
February 1, 2016 17:48
-
-
Save gavinwahl/812e6db78bfbf36dcaab to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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