Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

redis

I'm using the regular redis package in order to connect my Python code to my Redis server.

As part of my code I check if a string object is existed in my Redis server keys.

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

For some reasons, redis.keys() returns a list with bytes 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 it did not help.

My goal is to insert the data as string ahead, and not iterate over the keys list and change each element to str() while checking it.

Thanks ahead

like image 981
GMe Avatar asked May 17 '17 13:05

GMe


People also ask

Are Redis keys always strings?

Keys in Redis are all strings, so it doesn't really matter what kind of value you pass into a client.

How do you get all keys value to Redis?

Redis GET all Keys To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.


2 Answers

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

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

Make sure you are consistent with the charset option between clients.

Note

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

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

The KEYS operation returns every key in your Redis database and will cause serious performance degradation in production. As a side effect you avoid having to deal with the binary to string conversion.

like image 157
Tague Griffith Avatar answered Sep 18 '22 08:09

Tague Griffith


If you do not wish to iterate the list for decoding, set your redis connection to automagically perform the decode and you'll receive your required result. As follows in your connection string, please notice the decode_responses argument:

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

Happy Coding! :-) (revised 13 Nov 2019)

like image 43
RandallShanePhD Avatar answered Sep 17 '22 08:09

RandallShanePhD