🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
![](https://img.kancloud.cn/41/e0/41e066af9a6c25a24868d9667253ec98_1241x333.jpg) ***** ## Python操作Redis ### redispy安装及连接 安装 ``` pip install redis ``` 连接 ``` r = redis.StrictRedis(host='localhost',port=6379,db=0) ``` ### 字符串相关操作 ``` import redis class TestString(object): def __init__(self): self.r = redis.StrictRedis(host='192.168.75.130',port=6379) 设置值 def test_set(self): res = self.r.set('user1','juran-1') print(res) 取值 def test_get(self): res = self.r.get('user1') print(res) 设置多个值 def test_mset(self): d = { 'user2':'juran-2', 'user3':'juran-3' } res = self.r.mset(d) 取多个值 def test_mget(self): l = ['user2','user3'] res = self.r.mget(l) print(res) 删除 def test_del(self): self.r.delete('user2') ``` ### 列表相关操作 ``` class TestList(object): def __init__(self): self.r = redis.StrictRedis(host='192.168.75.130',port=6379) 插入记录 def test_push(self): res = self.r.lpush('common','1') res = self.r.rpush('common','2') # res = self.r.rpush('jr','123') 弹出记录 def test_pop(self): res = self.r.lpop('common') res = self.r.rpop('common') 范围取值 def test_range(self): res = self.r.lrange('common',0,-1) print(res) ``` ### 集合相关操作 ``` class TestSet(object): def __init__(self): self.r = redis.StrictRedis(host='192.168.75.130', port=6379) 添加数据 def test_sadd(self): res = self.r.sadd('set01','1','2') lis = ['Cat','Dog'] res = self.r.sadd('set02',lis) 删除数据 def test_del(self): res = self.r.srem('set01',1) 随机删除数据 def test_pop(self): res = self.r.spop('set02') ``` ### 哈希相关操作 ``` class TestHash(object): def __init__(self): self.r = redis.StrictRedis(host='192.168.75.130', port=6379) 批量设值 def test_hset(self): dic = { 'id':1, 'name':'huawei' } res = self.r.hmset('mobile',dic) 批量取值 def test_hgetall(self): res = self.r.hgetall('mobile') 判断是否存在 存在返回1 不存在返回0 def test_hexists(self): res = self.r.hexists('mobile','id') print(res) ```