1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
import redis
# # 连接,给定参数ip/port, redis默认端口6379
r = redis.Redis(host='127.0.0.1', port='6379')
# # print(type(r),r)
#
# # 设置键值对
r.set('name', 'admin')
# # 获取该键的值
str = r.get('name')
print(str.decode('utf-8')) # 解码
## 自动解码 参数:decode_responses=True
r = redis.Redis(host='127.0.0.1',port='6379',decode_responses=True)
r.set('name','哈哈')
str = r.get('name')
print(str)
## StrictRedis
r = redis.StrictRedis(host='127.0.0.1',port='6379')
r.set('name','哈哈')
str = r.get('name')
print(str,str.decode('utf-8'))
## `Redis`和`StrictRedis`区别:Redis兼容旧版本python2
#
k_v = {
'a1':'a',
'a2':'b',
'a3':'c'
}
r = redis.StrictRedis(host='127.0.0.1',port='6379')
# 批量设置值
r.mset(**k_v)
# 批量取值
print(r.mget('a1','a2','a3'))
#
r = redis.StrictRedis(host='127.0.0.1',port='6379')
# 往列表添加值从头部开始
r.lpush('list1','haha')
r.lpush('list1',3,4,5)
# 获取列表值
print(r.lrange('list1',0,-1))
#
r = redis.StrictRedis(host='127.0.0.1',port='6379')
r.sadd('set1','aa')
r.sadd('set2','aa',8,10,'bb')
print(r.smembers('set2'))
|