Skip to content

Commit b9544af

Browse files
laixintaoandymccurdy
authored andcommitted
add keepttl option to set command.
fixes #1304 fixes #1280
1 parent 9c8be70 commit b9544af

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

CHANGES

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
* Reset the watched state of pipelines after calling exec. This saves
2222
a roundtrip to the server by not having to call UNWATCH within
2323
Pipeline.reset(). Thanks @nickgaya, #1299/#1302
24+
* Add the KEEPTTL option for the SET command. Thanks @laixintao #1304/#1280
2425
* 3.4.1
2526
* Move the username argument in the Redis and Connection classes to the
2627
end of the argument list. This helps those poor souls that specify all

redis/client.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1761,7 +1761,8 @@ def restore(self, name, ttl, value, replace=False):
17611761
params.append('REPLACE')
17621762
return self.execute_command('RESTORE', *params)
17631763

1764-
def set(self, name, value, ex=None, px=None, nx=False, xx=False):
1764+
def set(self, name, value,
1765+
ex=None, px=None, nx=False, xx=False, keepttl=False):
17651766
"""
17661767
Set the value at key ``name`` to ``value``
17671768
@@ -1774,6 +1775,9 @@ def set(self, name, value, ex=None, px=None, nx=False, xx=False):
17741775
17751776
``xx`` if set to True, set the value at key ``name`` to ``value`` only
17761777
if it already exists.
1778+
1779+
``keepttl`` if True, retain the time to live associated with the key.
1780+
(Available since Redis 6.0)
17771781
"""
17781782
pieces = [name, value]
17791783
if ex is not None:
@@ -1791,6 +1795,10 @@ def set(self, name, value, ex=None, px=None, nx=False, xx=False):
17911795
pieces.append('NX')
17921796
if xx:
17931797
pieces.append('XX')
1798+
1799+
if keepttl:
1800+
pieces.append('KEEPTTL')
1801+
17941802
return self.execute_command('SET', *pieces)
17951803

17961804
def __setitem__(self, name, value):

tests/test_commands.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -867,6 +867,15 @@ def test_set_multipleoptions(self, r):
867867
assert r.set('a', '1', xx=True, px=10000)
868868
assert 0 < r.ttl('a') <= 10
869869

870+
@skip_if_server_version_lt('5.9.0') # 6.0-rc1
871+
def test_set_keepttl(self, r):
872+
r['a'] = 'val'
873+
assert r.set('a', '1', xx=True, px=10000)
874+
assert 0 < r.ttl('a') <= 10
875+
r.set('a', '2', keepttl=True)
876+
assert r.get('a') == b'2'
877+
assert 0 < r.ttl('a') <= 10
878+
870879
def test_setex(self, r):
871880
assert r.setex('a', 60, '1')
872881
assert r['a'] == b'1'

0 commit comments

Comments
 (0)