Redis与Python的交互

驱动模块

  • redis模块用来在Python环境下驱动Redis数据库
  • 可以直接用pip方式安装
pip install redis

或者国内镜像下载:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package

创建连接

import redis
con = redis.Redis(
    host="localhost",
    port="6379",
    password="123456",
    db=0
)

redis连接池

  • 创建连接池
import redis
pool = redis.ConnectionPool(
    host="localhost",
    port="6379",
    password="123456",
    db=0
    max_connection=20
)
  • redis连接池操作完成后不需要关闭连接,用del删除连接对象后会自动归还到连接池
con = redis.Redis(
    connection_pool=pool
)
......
del con

redis操作命令

  • 字符串
con.set("country","中国")
con.set("city","上海)
city = con.get("city").decode('utf-8')
print(city)
con.delete("city")
con.mset("countyr":"中国","city":"上海")
result = con.mget("country","city")
for one in result:
    print(one.decode('utf-8'))
  • 哈希
con.hmset("86",{"country":"中国","city":"上海","code":"200000"})
con.hset("86","age":"70")
con.hdel("86","code")
con.hexists("86","city")
result = con.hgetall("86")
for one in result:    
    print(one.decode("utf-8"))
  • 列表
con.rpush("courtry","中国","日本","韩国","印度")
con.lpop("country")
result = con.lrange("country",0,-1)
for one in result:
    print(one.decode('utf-8'))
  • 集合
con.sadd("courtry","中国","日本","韩国","印度")
con.rem("country","中国")
result = con.smembers("country")
for one in result:
    print(one.decode('utf-8'))
  • 有序集合
con.zadd("country",{"中国":"0","日本":"0","韩国":"0"})
con.zincrby("country","10","中国")
result = con.zrevrange("country",0,-1)
for one in result:
    print(one.decode('utf-8'))

redis-py的事务函数

  • redis-py模块用pipline(管道)的方式向redis服务器传递批处理命令和执行事务
pipline = con.pipline()
pipline.watch(......)
pipline.multi()
pipline.execute()
pipline.reset()

redis数据库异常处理和事务结合案例

import redis

pool = redis.ConnectionPool(
    host="localhost",
    port="6379",
    password="123456",
    db=0
    max_connection=20
)

con = redis.Redis(
    connection_pool=pool
)
pipline=con.pipline()

try:
    pip.watch("country")
    pip.multi()
    pipline.zincrby("country","1","中国")
    pipline.execute()
except Exception as e:
    print(e)
finally:
    if "pipline" in dir():
        pipline.reset()
    del con

转载于:https://www.cnblogs.com/felixqiang/p/11111998.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值