Skip to content
Permalink
Browse files

add keepttl option to set command.

fixes #1304
fixes #1280
  • Loading branch information
laixintao authored and andymccurdy committed Mar 10, 2020
1 parent 9c8be70 commit b9544af2c8eb85fcbe11137e6b0797066e3d718f
Showing with 19 additions and 1 deletion.
  1. +1 −0 CHANGES
  2. +9 −1 redis/client.py
  3. +9 −0 tests/test_commands.py
@@ -21,6 +21,7 @@
* Reset the watched state of pipelines after calling exec. This saves
a roundtrip to the server by not having to call UNWATCH within
Pipeline.reset(). Thanks @nickgaya, #1299/#1302
* Add the KEEPTTL option for the SET command. Thanks @laixintao #1304/#1280
* 3.4.1
* Move the username argument in the Redis and Connection classes to the
end of the argument list. This helps those poor souls that specify all
@@ -1761,7 +1761,8 @@ def restore(self, name, ttl, value, replace=False):
params.append('REPLACE')
return self.execute_command('RESTORE', *params)

def set(self, name, value, ex=None, px=None, nx=False, xx=False):
def set(self, name, value,
ex=None, px=None, nx=False, xx=False, keepttl=False):
"""
Set the value at key ``name`` to ``value``
@@ -1774,6 +1775,9 @@ def set(self, name, value, ex=None, px=None, nx=False, xx=False):
``xx`` if set to True, set the value at key ``name`` to ``value`` only
if it already exists.
``keepttl`` if True, retain the time to live associated with the key.
(Available since Redis 6.0)
"""
pieces = [name, value]
if ex is not None:
@@ -1791,6 +1795,10 @@ def set(self, name, value, ex=None, px=None, nx=False, xx=False):
pieces.append('NX')
if xx:
pieces.append('XX')

if keepttl:
pieces.append('KEEPTTL')

return self.execute_command('SET', *pieces)

def __setitem__(self, name, value):
@@ -867,6 +867,15 @@ def test_set_multipleoptions(self, r):
assert r.set('a', '1', xx=True, px=10000)
assert 0 < r.ttl('a') <= 10

@skip_if_server_version_lt('5.9.0') # 6.0-rc1
def test_set_keepttl(self, r):
r['a'] = 'val'
assert r.set('a', '1', xx=True, px=10000)
assert 0 < r.ttl('a') <= 10
r.set('a', '2', keepttl=True)
assert r.get('a') == b'2'
assert 0 < r.ttl('a') <= 10

def test_setex(self, r):
assert r.setex('a', 60, '1')
assert r['a'] == b'1'

0 comments on commit b9544af

Please sign in to comment.
You can’t perform that action at this time.