Python 基础教程

Python 高级教程

Python 相关应用

Python 笔记

Python FAQ

original icon
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.knowledgedict.com/tutorial/python-redis-binary-result-decode.html

python redis 模块查询数据结果 bytes 类型转码的方法

Python 笔记 Python 笔记


通过使用 python redis 模块的 client 进行数据获取时,如果没有专门设置,会获取到 b 开头的二进制类型,这是因为 redis 模块客户端交互时默认是 bytes 类型存储,其实初始化连接对象时,提供了类型解码的参数。

解决方法

Redis 类构造函数提供了用于数据结果解码的参数 decode_responses,将其设置为 True 即可。

采用默认时,打印显示结果如下:

import redis

conn = redis.Redis(
    host='xxxx.xxxxx.xxx',
    port=6379,
    password='xxxxxx'
)
result = conn.hgetall('knowledgedict')
print('result', result)
result {b'impression': b'7', b'click': b'1', b'ctr': b'0.1429'}

通过设置 decode_responses=True 后,结果显示如下:

import redis

conn = redis.Redis(
    host='xxxx.xxxxx.xxx',
    port=6379,
    password='xxxxxx',
    decode_responses=True
)
result = conn.hgetall('knowledgedict')
print('result', result)
result {'impression': 7, 'click': '1', 'ctr': '0.1429'}