Python-redis keys () returns a list of byte objects instead of strings

I use the regular redis package to connect my Python code to my Redis server.

As part of my code, I check to see if a string object exists in my Redis server keys.

 string = 'abcde' if string in redis.keys(): do something.. 

For some reason, redis.keys () returns a list with byte objects such as [b'abcde'] , while my string is, of course, a str object.

I already tried to set charset , encoding and decode_responses in my redis generator, but that didn't help.

My goal is to insert the data as a string ahead, rather than iterating over the list of keys and changing each element to str (), checking it.

thanks in advance

+5
source share
2 answers

You would be better off using the EXISTS command and restructuring your code as follows:

 string = 'abcde' if redis.exists(string): do something.. 

The KEYS operation returns every key in your Redis database and will seriously degrade production performance. As a side effect, you avoid dealing with converting binary to string.

You can configure the Redis client to automatically convert responses from bytes to strings using the decode_responses argument to the decode_responses constructor:

 r = redis.StrictRedis('localhost', 6379, charset="utf-8", decode_responses=True) 

Make sure you agree with the charset option between clients.

+7
source

If you do not want to iterate over the list for decoding, set up your redis connection to automatically perform decoding, and you will get the desired result. As indicated in your connection string, pay attention to the decode_responses argument:

 rdb = redis.StrictRedis(host="localhost", charset="utf-8", port=6379, db=0, decode_responses=True) 

Happy coding !:-)

+6
source

All Articles