Python 与 redis 交互取出数据类型是 bytes 时,如何直接取出 str 数据类型

2023-02-18 10:42:08 浏览数 (1)

运行代码:(存 str 类型,得 bytes 类型,这是由于 Python3 与 redis 交互的驱动的问题,Python2 取出来的就是 str 类型的)

代码语言:javascript复制
[root@VM_2_29_centos ~]# workon
blog
Joyo
testdata
[root@VM_2_29_centos ~]# workon Joyo
(Joyo) [root@VM_2_29_centos ~]# python
[root@VM_2_29_centos ~]# python3
Python 3.6.4 (default, Mar 16 2018, 22:27:18) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from redis import *
>>> sr = StrictRedis(host='localhost', port=6379, db=0)
>>> sr
StrictRedis<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>
>>> res = sr.set("name", "python")
>>> print(res)
True
>>> res1 = sr.get("name")
>>> print(res1)
b'python'
>>>

修改连接配置参数即可直接得到 str :(增加 decode_responses=True)

代码语言:javascript复制
>>> sr1 = StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
>>> sr1
StrictRedis<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>
>>> res2 = sr1.set("name3","python3")
>>> print(res2)
True
>>> res3 = sr1.get("name3")
>>> print(res3)
python3
>>>

0 人点赞