Driving module
- redis Module is used to drive Redis database in Python environment
- Can be installed directly in pip mode
pip install redis
Or download domestic image:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package
Create connection
import redis con = redis.Redis( host="localhost", port="6379", password="123456", db=0 )
redis connection pool
- Create connection pool
import redis pool = redis.ConnectionPool( host="localhost", port="6379", password="123456", db=0 max_connection=20 )
- After the redis connection pool operation is completed, you do not need to close the connection. After deleting the connection object with del, it will automatically return to the connection pool.
con = redis.Redis( connection_pool=pool ) ...... del con
redis operation command
- Character string
con.set("country","China") con.set("city","Shanghai) city = con.get("city").decode('utf-8') print(city) con.delete("city")
con.mset("countyr":"China","city":"Shanghai") result = con.mget("country","city") for one in result: print(one.decode('utf-8'))
- Hash
con.hmset("86",{"country":"China","city":"Shanghai","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"))
- list
con.rpush("courtry","China","Japan","The Republic of Korea","India") con.lpop("country") result = con.lrange("country",0,-1) for one in result: print(one.decode('utf-8'))
- aggregate
con.sadd("courtry","China","Japan","The Republic of Korea","India") con.rem("country","China") result = con.smembers("country") for one in result: print(one.decode('utf-8'))
- Ordered set
con.zadd("country",{"China":"0","Japan":"0","The Republic of Korea":"0"}) con.zincrby("country","10","China") result = con.zrevrange("country",0,-1) for one in result: print(one.decode('utf-8'))
Transaction function of redis PY
- The redis py module uses pipeline to deliver batch commands and execute transactions to the redis server.
pipline = con.pipline() pipline.watch(......) pipline.multi() pipline.execute() pipline.reset()
Case study on the combination of redis database exception handling and transaction
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("xxx") pip.multi() pipline.zincrby("country","1","China") pipline.execute() except Exception as e: print(e) finally: if "pipline" in dir(): pipline.reset() del con