手记

【九月打卡】第四天 Redis与Python的交互

学习课程:Python全能工程师2022版

章节名称:第10周 Redis数据库 Redis与Python的交互

讲师:神思者


课程内容:

关于Redis

开源免费,基于Key-Value存储数据

NoSQL数据库(Not Only SQL)中的一种

数据存储在内存,可以持久化至硬盘保存

高效的数据结构:String,hash,list,set,zset

高速缓存:10w+的QPS(查询次数/秒),集群可达百万级以上


关于redis-py

使用redis-py管理Redis数据库

python默认解析器PythonParser,可以安装C语言实现的HiredisParser


安装redis-py

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

帮助文档主页 https://pypi.org/project/redis/


连接方式

1、直接连接

创建连接

import redis

r=redis.Redis(host="localhost",port=6379,password="abc123456",db=0)

设置自动转码

r=redis.Redis(host="localhost",port=6379,password="abc123456",db=0,decode_responses=True)


2、使用连接池连接

创建连接池pool=redis.ConnectionPool(host="localhost",port=6379,password="abc123456",db=0,max_connections=20)

从连接池中获取的连接,不用关闭,垃圾回收的时候,连接会自动被归还到连接池

r=redis.Redis(connection_pool=pool)

del r

关闭连接,回收放回连接池

r.close()

一般使用try except finally 语句进行操作,del r 或r.close()放在finally中


操作命令

r.set("country","英国")

r.set("city","伦敦")

city=r.get("city").decode("utf-8")

r.delete("country","city")

r.mset({"country":"德国","city":"柏林"})

result=r.mget("country","city")

for one in result:

print(one.decode("utf-8"))

r.rpush("dname","a","b","c")

r.lpop("dname")

result=r.lrange("dname",0,-1)

for one in result:

    print(one.decode("utf-8"))

r.hmse("9527",{"name":"Scott","sex":"male","age":"35"})

r.hset("9527","city","纽约")

r.hdel("9527","age")

r.hexists("9527","name")

result=r.hgetall("9527")



学习收获:

1、了解了redis-py的常用操作

2、了解了redis常见错误和解决方法


打卡截图:


0人推荐
随时随地看视频
慕课网APP