Redis-py and hgetall behavior

I played with flash microframes and wanted to cache some statistics in redis. Let's say I have this dict:

mydict = {} mydict["test"] = "test11" 

I saved it for redis using

 redis.hmset("test:key", mydict) 

However after recovery

 stored = redis.hgetall("test:key") print(str(stored)) 

I see weird {b'test': b'test11'} , so stored.get("test") gives me None

mydict The result of the str method looks great {'test': 'test11'} . So why is this binary marker added to the recovered data? I also checked in redis-cli and don't see explicit b-labels there. Is there something wrong with hgetall?

+7
redis redis-py
source share
2 answers

This is the intended behavior. By default, lines coming out of Redis do not receive decryption. You have several options:

  • Decrypt the data yourself.
  • Create a client instance with the decode_responses argument, for example, StrictRedis(decode_responses=True) . This will decode all the lines that come from Redis based on the charset argument (which is by default to utf-8). Only in this way are you sure that every response from Redis is the string data that you want to decode in utf-8. If you use the same client instance to receive binary data, such as a pickled object, you should not use this option. In this case, I would suggest using a separate client instance for binary data.

Source: https://github.com/andymccurdy/redis-py/issues/463#issuecomment-41229918

+13
source share
 POOL = redis.ConnectionPool(host='localhost', **decode_responses=True**, port=6379, db=0) datastore = redis.StrictRedis(connection_pool=POOL) 

if you use ConnectionPool, you must move decode_responses = True to the ConnectionPool constructor.

+2
source share

All Articles