Skip to content

Commit

Permalink
Merge pull request #16 from tbarbugli/master
Browse files Browse the repository at this point in the history
use LUA to increase and expire keys safely
  • Loading branch information
alisaifee authored Oct 29, 2016
2 parents 8b022fc + fe6d1bc commit d9f3970
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions limits/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,15 @@ class RedisInteractor(object):
return res
"""

SCRIPT_INCR_EXPIRE = """
local current
current = redis.call("incr",KEYS[1])
if tonumber(current) == 1 then
redis.call("expire",KEYS[1],ARGV[1])
end
return current
"""

def incr(self, key, expiry, connection, elastic_expiry=False):
"""
increments the counter for a given rate limit key
Expand Down Expand Up @@ -376,6 +385,9 @@ def initialize_storage(self, uri):
self.lua_clear_keys = self.storage.register_script(
self.SCRIPT_CLEAR_KEYS
)
self.lua_incr_expire = self.storage.register_script(
RedisStorage.SCRIPT_INCR_EXPIRE
)

def incr(self, key, expiry, elastic_expiry=False):
"""
Expand All @@ -384,9 +396,12 @@ def incr(self, key, expiry, elastic_expiry=False):
:param str key: the key to increment
:param int expiry: amount in seconds for the key to expire in
"""
return super(RedisStorage, self).incr(
key, expiry, self.storage, elastic_expiry
)
if elastic_expiry:
return super(RedisStorage, self).incr(
key, expiry, self.storage, elastic_expiry
)
else:
return self.lua_incr_expire([key], [expiry])

def get(self, key):
"""
Expand Down

0 comments on commit d9f3970

Please sign in to comment.