python_redis

python + redis —–> redis

"""
redis值类型   对应python类型
0 1       -->   0 1
数字       --》  int  float
列表       -->   列表
字符串      --》  字节串
哈希       -->   字典

"""

import redis

''' 通 用 类 型  '''
# 通用指令
def generic():
    # 通用指令
    res = r.keys("*")
    print(res)
    print(r.exists("name"))
    r.delete("sset")

''' 字 符 串 '''
# 字符串指令
def string():
    r.set("name", "zhaoliying")
    res = r.get("name")
    print(res.decode())
    r.mset({"a": 1, 'b': 2})
    print(r.mget("a", 'b'))
    r.incrby('a', 10)


def list_cmd():
    # r.lpush("mylist",1,2,3,4,5) # 添加值
    print(r.lrange('mylist', 0, -1))

    r.lpop('mylist')  # 删除第一个
    print(r.llen('mylist'))


''' 哈 希 表 '''
# 哈希类型操作
def hash_cmd():
    # r.hset("myhash","name","张三")
    # r.hset("myhash",mapping={"age":10,"score":8.8})

    res = r.hget('myhash', "name")
    print(res.decode())

    res = r.hgetall('myhash')
    print(res)

    r.hdel("myhash", "sex")  # 删除一个键值对

''' 集合 '''
def set_cmd():
    # r.sadd("武将","张飞","赵云","周瑜","马超")
    # r.sadd("文臣","诸葛亮","周瑜","司马懿","郭嘉")

    # 返回一个集合
    print(r.smembers("武将"))

    # 求交集  并集
    print({i.decode() for i in r.sinter("武将", "文臣")})
    print({i.decode() for i in r.sunion("武将", "文臣")})


# 有序集合
def sortedset_cmd():
    # r.zadd("starset1",{"霍元甲":10,"陈真":9})
    # r.zadd("starset2",{"李小龙":9.5,"陈真":9})

    res = r.zrange("starset1", 0, -1, withscores=True)
    # 字典推导式  [(xx,8),()]
    print({k.decode(): float(v) for k, v in res})

    # ZUNIONSTORE  newset  2   set1  set2  weights  0.6  0.8  aggregate  max
    res = r.zunionstore("newset1", {"starset1": 0.6, "starset2": 0.8}, aggregate="MAX")
    print(res)  # 新集合元素数量
    res = r.zrange("newset1", 0, -1, withscores=True)
    print({k.decode(): float(v) for k, v in res})


if __name__ == '__main__':
    # 连接数据库 host  port  db  password  charset
    r = redis.Redis(
        host='192.168.227.137',
        port=6379,
        db=0
    )

    # 数据操作  命令-》方法   命令参数-》方法参数

    # 通用指令
    # generic()

    # 字符串指令
    # string()

    # 列表指令
    # list_cmd()

    # 哈希操作
    # hash_cmd()

    # 集合类型
    # set_cmd()

    # 有续集和
    # sortedset_cmd()

    print('操作完成')
    # 关闭连接
    r.close()
github