From b9544af2c8eb85fcbe11137e6b0797066e3d718f Mon Sep 17 00:00:00 2001 From: laixintao Date: Tue, 10 Mar 2020 12:04:36 +0800 Subject: add keepttl option to set command. fixes #1304 fixes #1280 --- CHANGES | 1 + redis/client.py | 10 +++++++++- tests/test_commands.py | 9 +++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/CHANGES b/CHANGES index 32e8b95..a3c4fcf 100644 --- a/CHANGES +++ b/CHANGES @@ -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 diff --git a/redis/client.py b/redis/client.py index 9f75465..1393a1c 100755 --- a/redis/client.py +++ b/redis/client.py @@ -1761,7 +1761,8 @@ class Redis(object): 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 @@ class Redis(object): ``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 @@ class Redis(object): pieces.append('NX') if xx: pieces.append('XX') + + if keepttl: + pieces.append('KEEPTTL') + return self.execute_command('SET', *pieces) def __setitem__(self, name, value): diff --git a/tests/test_commands.py b/tests/test_commands.py index 3742edf..3132903 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -867,6 +867,15 @@ class TestRedisCommands(object): 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' -- cgit v1.2.1