本来是想简单测试一下python-redis的字符串数据类型的操作,乍一看是没什么问题,成功输入输出,但仔细一看,输入输出的数据类型不一样,输入字符串,却输出bytes。
最开始使用的测试代码如下:
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
print(r.append('foo', ' bar'))
print(r.get('foo'))
输出结果如下:
7
b'bar bar'
检测了一下输出的数据类型确实是bytes:
print(type(r.get('foo')))
----------------------------------------------------------------
<class 'bytes'>
首先想到的是用decode解码,但要在所有必要的地方都使用decode解码,这也太麻烦了吧。
然后去看了class redis.Redis
的源码,发现两个参数:
也就是说,redis在初始化连接时通过encoding='utf-8'
默认使用utf-8
存储,然后通过decode_responses=False
默认关闭解码。
所以这里只需要设置decode_responses=True
。
测试代码如下:
import redis
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
r.set('foo', 'bar')
print(r.append('foo', ' bar'))
print(r.get('foo'))
print(type(r.get('foo')))
结果如下:
7
bar bar
<class 'str'>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/98103.html