Python 连接Redis进行 get、set 操作

#-*- coding: utf-8 -*-
'''
======================================================================
描述:python的redis连接操作案例
作者:xiawp
日期:2019/1/25 10:10:46
收获:引用redis模块连接redis服务。
		  通过 get()、set() 操作redis字符型数据;
		  通过 hset()、hget() 操作redis哈希类型数据
		  通过 json.dumps() 和 json.loads() 可以实现python中的字典数据的序列化和反序列化;
======================================================================
'''
import json
import redis

# decode_responses=True 设置响应数据自动解码,否则redis取出的数据都是 bytes 类型
localRedis = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)

# set字符型数据到redis
localRedis.set("testlocalhost", "127.0.0.1")
# python中的字典类型数据需要先通过 json.dumps 转换成字符串(json序列化操作)
localRedis.hset("testObject","001",json.dumps({"name":"张三" ,"year":1987, "city":"北京"}))

# 获取所有的key名
keyList = localRedis.keys()

# 遍历打印key对应value,通过get(key)不能获取字符存储类型以外的数据,因此需要加异常处理
for key in keyList:
	print ("Type Of",type(key),"key = ",key,end=" , ")
	try:
		print ("value = ",localRedis.get(key))
	except Exception as e:
		print ()
		print ("== redis.get(%s) 发生异常:"%(key),str(e))
	
# 通过 json.loads() 将json格式字符串数据转换成字典数据类型(json反序列化操作)
dirctObj = json.loads(localRedis.hget("testObject","001"))

print (dirctObj)
print ("001 的名字:", dirctObj["name"])

print ("\nThe End!")


'''
执行结果:
------------------------------------------------------------------------------------------------------------------------
---------- python ----------
Type Of <class 'str'> key =  hellokey , value =  helloTest....
Type Of <class 'str'> key =  testlocalhost , value =  127.0.0.1
Type Of <class 'str'> key =  testkey , value =  test...
Type Of <class 'str'> key =  testObject , 
== redis.get(testObject) 发生异常: WRONGTYPE Operation against a key holding the wrong kind of value
{'name': '张三', 'year': 1987, 'city': '北京'}
001 的名字: 张三

The End!

输出完成 (耗时 0 秒) - 正常终止
------------------------------------------------------------------------------------------------------------------------
'''

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值