Python3: interact with redis, save the string, take out the bytes type

 Reason: In python3, the redis connection package reads data by default and returns the byte type. What is stored in is string type data, but what is taken out is byte type.

            What Python2 takes out is the string type.

import platform

import redis

if "inux" in platform.system():
    print("检测到是服务器环境,启动redis内网链接")
    IP = "xxx.xx.x.xx"
    PORT = 6379
else:
    IP = "xxx.xxx.xxx.xx"
    PORT = 6379
# 存进去的是字符串类型的数据,取出来却是字节类型的
redisPool1 = redis.ConnectionPool(host=IP, port=PORT, db=1, password="xxxxxxx")

if __name__ == '__main__':
    client = redis.Redis(connection_pool=redisPool1 )
    client.set("ACCESS_TOKEN", "ABC123456", 60 * 60)
    token = client.get("ACCESS_TOKEN")
    print(token)  # b'ABC123456'
    print(type(token))  # <class 'bytes'>

Solution: When connecting to redis, add decode_responses=True or decode it every time you take it out (too troublesome, not recommended)

import platform

import redis

if "inux" in platform.system():
    print("检测到是服务器环境,启动redis内网链接")
    IP = "xxx.xx.x.xx"
    PORT = 6379
else:
    IP = "xxx.xxx.xxx.xx"
    PORT = 6379
# 存进去的是字符串类型的数据,取出来也是字符型
redisPool1 = redis.ConnectionPool(host=IP, port=PORT, db=1, password="xxxxxxx", decode_responses=True)

if __name__ == '__main__':
    client = redis.Redis(connection_pool=redisPool1 )
    client.set("ACCESS_TOKEN", "ABC123456", 60 * 60)
    token = client.get("ACCESS_TOKEN")
    print(token)  # ABC123456
    print(type(token))  # <class 'str'>

 

Guess you like

Origin blog.csdn.net/weixin_38676276/article/details/107773595