首页 > 代码库 > redis-py中的坑

redis-py中的坑

今天发现,使用redis-py从redis中获取的数据竟然是加密的。

conn = redis.Redis(host=redis_serverip, port=6379, password=redis_password, db=0)

conn.set(string-key1, value1)

result = conn.get(string-key1)
print(result:, result)
print(result type:, type(result))
print()

result_decoded = result.decode(utf-8)
print(result_decoded:, result_decoded)
print(result_decoded type:, type(result_decoded))
print()

result_str = str(result)
print(result_str:, result_str)
print(result_str type:, type(result_str))
print()

print(test int in redis...\n)

conn.set(string-key2, 100)
result = conn.get(string-key2)
print(result:, result)
print(result type:, type(result))
print()

result_decoded = int(result)
print(result_decoded:, result_decoded)
print(result_decoded type:, type(result_decoded))

输出:

result: b‘value1‘
result type: <class ‘bytes‘>

result_decoded: value1
result_decoded type: <class ‘str‘>

result_str: b‘value1‘
result_str type: <class ‘str‘>

test int in redis...

result: b‘100‘
result type: <class ‘bytes‘>

result_decoded: 100
result_decoded type: <class ‘int‘>

 

可以看出:

如果传入str,传出的是bytes,需要通过decode(‘utf-8‘)进行恢复。

如果传入int,传出的是bytes,需要通过int()进行恢复。

 

另一种解决办法是在创建redis client时,进行decode设置。

conn = redis.Redis(host=redis_serverip, port=6379, password=redis_password, db=0, decode_responses=True)

conn.set(string-key3, value3)

result = conn.get(string-key3)
print(result:, result)
print(result type:, type(result))
print()

print(test int in redis...\n)

conn.set(string-key4, 100)

result = conn.get(string-key4)
print(result:, result)
print(result type:, type(result))
print()

result_decoded = int(result)
print(result_decoded:, result_decoded)
print(result_decoded type:, type(result_decoded))

输出:

result: value3
result type: <class ‘str‘>

test int in redis...

result: 100
result type: <class ‘str‘>

result_decoded: 100
result_decoded type: <class ‘int‘>

这种情况下,str是正常的,int需要注意一下。

 

参考资料:

Problem with hash get/set

redis-py中的坑