本来是想简单测试一下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'>