Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to overwrite (replace) a redis list in python

Tags:

python

redis

I need to store a python list (order is important) in a Redis. Currently, I use the following code to do this:

import redis
redis_conn = redis.StrictRedis(host='localhost', port=6379)

r = redis_conn.rpush('key', *a_python_list)

But I need to overwrite (replace) the current key (current stored list values) with new values each time I run the python script instead of appending the list to the previous values for that key. I know that I can delete the whole old list by removing the stored key and rpush the list again using the following code:

import redis
redis_conn = redis.StrictRedis(host='localhost', port=6379)

if redis_conn.exists('key'):
    redis_conn.delete(redis_key)

r = redis_conn.rpush('key', *a_python_list)

I want to know that if there is a built-in redis command (or a better way) to replace the whole of existing list with the new list for a key instead of appending it?

like image 880
Amir Masoud Avatar asked Jun 24 '26 06:06

Amir Masoud


1 Answers

Using a redis pipeline wraps in a transaction:

import redis
r = redis.Redis()

with r.pipeline() as pipe:
    pipe.delete('foo')
    pipe.rpush('foo', *[1, 2, 3, 4])
    pipe.execute()
like image 95
shapiromatron Avatar answered Jun 25 '26 18:06

shapiromatron