python语言保存字典到redis的正确姿势

2021-04-21  本文已影响0人  乐享书

字典是python中一种常见的数据格式,我们也常需要对这些数据做缓存。一般采用保存到redis实现。 但是redis库的set, get方法不支持字典,只支持二进制或者字符串。 所以网上一般都采用转换为字典或字符串的形式,比较麻烦。
其实redis 的还支持hash处理。
例子如下:

import redis  

redis_pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
redis_client = redis.Redis(connection_pool=redis_pool)
redis_client.set('status', 'up')
print(redis_client.get('status'))
print(type(redis_client.get('status')))

d = {'a':1}
redis_client.hmset('d', d)
print(redis_client.hgetall('d'))
print(type(redis_client.hgetall('d')))

上一篇 下一篇

猜你喜欢

热点阅读