基于Pycharm与数据库的新闻管理系统(2)Redis

pip3 install redis

1.创建 Redis 连接池

文件地址:db/redis_db.py

代码尝试连接到本地运行的 Redis 服务器,并设置数据库为 1,最大连接数为 20。

如果连接过程中出现任何异常,它会捕获异常并打印错误信息。

import redis
try:
    pool = redis.ConnectionPool(
        host='localhost',
        port=6379,
        db=1,
        max_connections=20
    )
except Exception as e:
    print(e)

2.查找用于缓存的记录

文件地址:db/news_dao.py

用 sql 语言在 Navicat 中寻找要作为缓存的记录,

目的是将审批通过的信息,存进 Redis 数据库中。

    #查找用于缓存的记录
    def search_cache(self, id):
        # 创建异常
        try:
            # 获得连接项
            conn = pool.get_connection()
            # 获得游标
            cursor = conn.cursor()
            # 创建sql
            sql = """
               SELECT n.title,u.username,t.type,n.content_id,n.is_top,n.create_time
                FROM t_news n join t_type t on n.type_id=t.id
                join t_user u on n.editor_id=u.id
                where n.id=%s
            """
            # 执行sql
            cursor.execute(sql, [id])
            # 获得查询结果
            result = cursor.fetchone()
            return result
        # 返回获得结果
        except Exception as e:
            print(e)
        finally:
            if "conn" in dir():
                conn.close()

3.操作Redis数据库

3.1 创建操作类

文件地址:db/redis_news_dao.py

创建一个 Python 类 RedisNewsDao,它包含两个方法:insertdelete

分别用于添加与删除 Redis 数据库中的新闻数据。

3.1.1 添加数据

from db.redis_db import pool
import redis
class RedisNewsDao:
    #添加数据
    def insert(self,id,title,username,type,content,is_top,create_time):
        conn = redis.Redis(
            connection_pool=pool,
        )
        try:
            #向redis中存放数据
            conn.hmset(id,{
                'title':title,
                'author':username,
                'type':type,
                'content':content,
                'is_top':is_top,
                'create_time':create_time
            })
            #如果是今日热文则保留一天后销毁
            if is_top &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值