Python-redis keys() 返回字节对象列表而不是字符串 [英] Python-redis keys() returns list of bytes objects instead of strings
问题描述
我使用常规的 redis
包来将我的 Python 代码连接到我的 Redis 服务器.
I'm using the regular redis
package in order to connect my Python code to my Redis server.
作为代码的一部分,我检查 Redis 服务器密钥中是否存在字符串对象.
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..
由于某些原因,redis.keys() 返回一个包含字节对象的列表,例如 [b'abcde']
,而我的字符串当然是一个 str代码>对象.
For some reasons, redis.keys() returns a list with bytes objects, such as [b'abcde']
, while my string is, of course, a str
object.
我已经尝试在我的 redis 生成器中设置 charset
、encoding
和 decode_responses
,但没有帮助.
I already tried to set charset
, encoding
and decode_responses
in my redis generator, but it did not help.
我的目标是将数据作为字符串插入前面,而不是遍历键列表并在检查时将每个元素更改为 str().
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.
先谢谢了
推荐答案
您可以将 Redis 客户端配置为使用 StrictRedis
的 decode_responses
参数自动将响应从字节转换为字符串代码>构造函数:
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)
确保您与客户端之间的 charset
选项保持一致.
Make sure you are consistent with the charset
option between clients.
注意
您最好使用 EXISTS 命令并重构您的代码,例如:
You would be better off using the EXISTS command and restructuring your code like:
string = 'abcde'
if redis.exists(string):
do something..
KEYS 操作会返回您的 Redis 数据库中的每个键,并且会导致生产中的性能严重下降.作为一个副作用,您可以避免处理二进制到字符串的转换.
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.
这篇关于Python-redis keys() 返回字节对象列表而不是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!