Skip to content

Instantly share code, notes, and snippets.

@fiorix
Created February 13, 2012 00:14
Show Gist options
  • Save fiorix/1811995 to your computer and use it in GitHub Desktop.
Save fiorix/1811995 to your computer and use it in GitHub Desktop.
def checkQuota(method):
@defer.inlineCallbacks
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
key = "ip:%s" % self.request.remote_ip
try:
n = yield self.redis.incr(key)
except Exception, e:
log.msg("Redis failed to incr('%s'): %s" % (key, str(e)))
raise cyclone.web.HTTPError(503)
if n == 1:
try:
yield self.redis.expire(key, self.settings.expire)
except Exception, e:
log.msg("Redis failed to expire('%s', %d): %s" % \
(key, self.settings.expire, str(e)))
raise cyclone.web.HTTPError(503)
elif n > self.settings.max_requests:
# Over quota, take this.
raise cyclone.web.HTTPError(403) # Forbidden
yield defer.maybeDeferred(method, self, *args, **kwargs)
defer.returnValue(None)
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment