How to keep a list of dicts in Redis against a key using Python-redis. The following is the data structure which I am aiming at:
'browsing_history' : {
'session_key_1' : [{'image': 'image-url', 'url' : 'url', 'title' : 'test_title', 'description' : 'test_description'}, {''image': 'image-url2', 'url' : 'url2', 'title' : 'test_title2', 'description' : 'test_description2'}],
'session_key_2' : [{'image': 'image-url', 'url' : 'url', 'title' : 'test_title', 'description' : 'test_description'}, {''image': 'image-url2', 'url' : 'url2', 'title' : 'test_title2', 'description' : 'test_description2'}],
}
Would like to add into the session lists as well as add new sessions and also retrive them. How can I do this using Python-redis?
Use json to make a string representation of the dictionary, then store it as a value in the Redis database.
source code object --+ | StrictRedis. Implementation of the Redis protocol. This abstract class provides a Python interface to all Redis commands and an implementation of the Redis protocol. Connection and Pipeline derive from this, implementing how the commands are sent and received to the Redis server. Instance ...
Storing the object in two hash tables. Since hash tables in Redis can not be nested (a.k.a. need to be “flat”), you have to use two hash tables in order to store the house-object.
Serialize your dictionary {'image': 'image-url', 'url' : 'url', 'title' : 'test_title', 'description' : 'test_description'}
with pickle or json. Use redis list to store them as strings. Use keys like browsing_history:SESSION_KEY_1
to access those lists. If you need to get a list of all session keys you probably will need to maintain a set of strings for keys browsing_history:*
.
A solution not requiring serialization and not restricted by the limits on string sizes (but not necessarily more performant) is to store each dict in its own dedicated hash map:
# define root name for hashes used
# to store list elements - dicts
hash_root_name='test_hash'
# sample list of dicts
dicts_list=[test_dict1, test_dict2]
# store dicts from the list to consecutively
# named redis hashes, with list indices
# appended to hash root name
for i in range(len(dicts_list)):
redis_client.hmset(hash_root_name+str(i),
dicts_list[i])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With