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

news/2024/12/26 0:04:13/

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()# 创建sqlsql = """SELECT n.title,u.username,t.type,n.content_id,n.is_top,n.create_timeFROM t_news n join t_type t on n.type_id=t.idjoin t_user u on n.editor_id=u.idwhere n.id=%s"""# 执行sqlcursor.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 == 0 :conn.expire(id,24*60*60)except Exception as e:print(e)finally:del conn#删除数据def delete(self,id):conn = redis.Redis(connection_pool=pool)try:conn.delete(id)except Exception as e:print(e)finally:del conn

3.1.2 删除数据 

from db.redis_db import pool
import redis
class RedisNewsDao:#删除数据def delete(self,id):conn = redis.Redis(connection_pool=pool)try:conn.delete(id)except Exception as e:print(e)finally:del conn

3.2 创建业务类

文件地址:service/news_service.py

from db.news_dao import NewsDao
from db.redis_news_dao import RedisNewsDao
class NewsService:#实例化新闻Dao对象__news_dao = NewsDao()__redis_news_dao = RedisNewsDao()#查找用户管理中的记录def search_cache(self,id):result = self.__news_dao.search_cache(id)return result#向Redis中保存缓存的新闻def cache_news(self,id,title,username,type,content,is_top,create_time):self.__redis_news_dao.insert(id,title,username,type,content,is_top,create_time)#删除缓存新闻def delete_cache(self,id):self.__redis_news_dao.delete(id)

4.更改Navicat与Redis数据库 

4.1 创建操作类

# 删除新闻
def delete_by_id(self, id):try:conn = pool.get_connection()conn.start_transaction()cursor = conn.cursor()sql = "delete from t_news where id=%s"cursor.execute(sql, [id])conn.commit()except Exception as e:print(e)if "conn" in dir():conn.rollback()finally:if "conn" in dir():conn.close()# 添加新闻
def insert_news(self, title, editor_id, type_id, content_id, is_top):try:conn = pool.get_connection()conn.start_transaction()cursor = conn.cursor()sql = """insert into t_news(title,editor_id,type_id,content_id,is_top,state) values (%s,%s,%s,%s,%s,%s)"""cursor.execute(sql, (title, editor_id, type_id, content_id, is_top, "待审批"))conn.commit()except Exception as e:print(e)if "conn" in dir():conn.rollback()finally:if "conn" in dir():conn.close()# 查找用于缓存的记录
def search_cache(self, id):# 创建异常try:# 获得连接项conn = pool.get_connection()# 获得游标cursor = conn.cursor()# 创建sqlsql = """SELECT n.title,u.username,t.type,n.content_id,n.is_top,n.create_timeFROM t_news n join t_type t on n.type_id=t.idjoin t_user u on n.editor_id=u.idwhere n.id=%s"""# 执行sqlcursor.execute(sql, [id])# 获得查询结果result = cursor.fetchone()return result# 返回获得结果except Exception as e:print(e)finally:if "conn" in dir():conn.close()# 修改id查找新闻
def search_by_id(self, id):# 创建异常try:# 获得连接项conn = pool.get_connection()# 获得游标cursor = conn.cursor()# 创建sqlsql = """SELECT n.title,t.type,n.is_topFROM t_news n join t_type t on n.type_id=t.idwhere n.id=%s"""# 执行sqlcursor.execute(sql, [id])# 获得查询结果result = cursor.fetchone()return result# 返回获得结果except Exception as e:print(e)finally:if "conn" in dir():conn.close()# 更新修改新闻
def update(self, id, title, type_id, content_id, is_top):try:conn = pool.get_connection()conn.start_transaction()cursor = conn.cursor()sql = "update t_news set title=%s,type_id=%s,content_id=%s,is_top=%s,state=%s,update_time=now() where id=%s"cursor.execute(sql, (title, type_id, content_id, is_top, "待审批", id))conn.commit()except Exception as e:print(e)if "conn" in dir():conn.rollback()finally:if "conn" in dir():conn.close()

4.2  创建操作类

#删除新闻
def delete_news(self,id):self.__news_dao.delete_by_id(id)
#添加新闻
def insert_news(self,title,editor_id,type_id,content_id,is_top):self.__news_dao.insert_news(title, editor_id, type_id, content_id, is_top)
#查找用户管理中的记录
def search_cache(self,id):result = self.__news_dao.search_cache(id)return result
#向Redis中保存缓存的新闻
def cache_news(self,id,title,username,type,content,is_top,create_time):self.__redis_news_dao.insert(id,title,username,type,content,is_top,create_time)
#删除缓存新闻
def delete_cache(self,id):self.__redis_news_dao.delete(id)
#根据id查询新闻信息
def search_by_id(self,id):result = self.__news_dao.search_by_id(id)return result
#更新修改新闻信息
def update(self,id,title,type_id,content_id,is_top):self.__news_dao.update(id,title,type_id,content_id,is_top)self.delete_cache(id)

5.实现Redis操作

文件地址:app_py.py

5.1 添加数据

opt = input("\n\t请输入操作编号")  # 等待控制台输入
if opt == "prev" and page > 1:page += -1
elif opt == "next" and page < count_page:page += 1
elif opt == "back":break
elif int(opt) >= 1 and int(opt) <= 5:  # 由于控制台获得的是字符串类型,需要转换成数字类型进行比较# 获得新闻id值news_id = result[int(opt) - 1][0]  # 获得对应行数及列# 调用news_service的审批函数__news_service.update_unreview_news(news_id)# 新闻缓存 👇result = __news_service.search_cache(news_id)title = result[0]username = result[1]type = result[2]content_id = result[3]# 查询新闻正文content = "100"is_top = result[4]create_time = str(result[5])__news_service.cache_news(news_id, title, username, type, content, is_top, create_time)👆

5.2 删除数据

opt = input("\n\t请输入操作编号")  # 等待控制台输入
if opt == "prev" and page > 1:page += -1
elif opt == "next" and page < count_page:page += 1
elif opt == "back":break👇
elif int(opt) >=1 and int(opt) <=5 :news_id = result[int(opt) - 1][0]result = __news_service.search_by_id(news_id)title = result[0]type = result[1]is_top = result[2]print("\n\t新闻原标题:%s"%(title))new_title = input("\n\t新标题")print("\n\t新闻原类型:%s"%(type))result = __type_service.search_list()for index in range(len(result)):t = result[index]print(Fore.LIGHTBLUE_EX,"\n\t%d.%s"%(index+1,t[1]))print(Style.RESET_ALL)opt = input("\n\t类型编号:")new_type = result[int(opt) - 1][0]content_id = 10print("原置顶级别%s"%(is_top))new_is_top = input("\n\t置顶级别(0-5):")is_commit = input("\n\t是否提交?(Y/N)")if is_commit == 'y' or is_commit == 'Y':__news_service.update(news_id,new_title, new_type, content_id, new_is_top)print("\n\t保存成功(3秒自动返回)")time.sleep(3)👆

5.3 更改数据

print(Fore.LIGHTGREEN_EX," \n\t1.发表新闻")
print(Fore.LIGHTGREEN_EX, "\n\t2.编辑新闻")
print(Fore.LIGHTGREEN_EX, "\n\t3.退出登录")
print(Fore.LIGHTGREEN_EX, "\n\t4.退出系统")
print(Style.RESET_ALL)
opt = input("\n\t输入操作编号")
if opt == "1":...
elif opt == "2":
page = 1
while True:os.system("cls")count_page = __news_service.search_count_page()result = __news_service.search_list(page)for index in range(len(result)):new = result[index]print(Fore.LIGHTBLUE_EX, "\n\t%d\t%s\t%s\t%s\t" % (index + 1, new[1], new[2], new[3]))# 输入在新闻列表中一共有多少页,当前多少页print(Fore.LIGHTBLUE_EX, "\n\t%d/%d" % (page, count_page))print(Fore.LIGHTBLUE_EX, "\n\t------------------")print(Fore.LIGHTBLUE_EX, "\n\tprev.上一页")print(Fore.LIGHTBLUE_EX, "\n\tnext.下一页")print(Fore.LIGHTBLUE_EX, "\n\tback.返回上一层")print(Style.RESET_ALL)opt = input("\n\t请输入操作编号")  # 等待控制台输入if opt == "prev" and page > 1:page += -1elif opt == "next" and page < count_page:page += 1elif opt == "back":breakelif int(opt) >= 1 and int(opt) <= 5:news_id = result[int(opt) - 1][0]result = __news_service.search_by_id(news_id)title = result[0]type = result[1]is_top = result[2]print("\n\t新闻原标题:%s" % (title))new_title = input("\n\t新标题")print("\n\t新闻原类型:%s" % (type))result = __type_service.search_list()for index in range(len(result)):t = result[index]print(Fore.LIGHTBLUE_EX, "\n\t%d.%s" % (index + 1, t[1]))print(Style.RESET_ALL)opt = input("\n\t类型编号:")new_type = result[int(opt) - 1][0]content_id = 10print("原置顶级别%s" % (is_top))new_is_top = input("\n\t置顶级别(0-5):")is_commit = input("\n\t是否提交?(Y/N)")if is_commit == 'y' or is_commit == 'Y':__news_service.update(news_id, new_title, new_type, content_id, new_is_top)print("\n\t保存成功(3秒自动返回)")time.sleep(3)

http://www.ppmy.cn/news/1558121.html

相关文章

Sass变量的妙用:提升CSS开发效率与可维护性

Sass变量的妙用&#xff1a;提升CSS开发效率与可维护性 Sass变量的妙用&#xff1a;提升CSS开发效率与可维护性一、Sass变量的基础二、Sass变量的妙用三、提升开发效率与可维护性四、结论 Sass变量的妙用&#xff1a;提升CSS开发效率与可维护性 在前端开发的世界里&#xff0c…

动态规划子序列问题系列一>最长等差数列

题目&#xff1a; 解析&#xff1a; 1.状态表示&#xff1a; 2.状态转移方程&#xff1a; 该题痛点&#xff1a; 3.初始化&#xff1a; 把dp表全部初始化为2 4.填表顺序&#xff1a; 5.返回值&#xff1a;返回dp表里的最大值 代码&#xff1a; public int long…

Javascript手撕题目大全(回顾四)

1.如何使用JS实现Promise 对象?请写出具体代码 Promise其实也不难-CSDN博客 Javascript 手写一个Promise_javascript中手写promise ?-CSDN博客 如何使用 JS 实现 Promise 对象&#xff1f;请写出具体代码 - 前端手写代码面试题 - 面试鸭 - 程序员求职面试刷题神器 题目要求我…

【Visual Studio Code(VSCode)介绍】

Visual Studio Code&#xff08;VSCode&#xff09;介绍 引言 在现代软件开发领域&#xff0c;集成开发环境&#xff08;IDE&#xff09;是程序员不可或缺的工具之一。Visual Studio Code&#xff08;简称VSCode&#xff09;&#xff0c;由微软开发&#xff0c;是一个轻量级但…

Artec Space Spider助力剑桥研究团队解码古代社会合作【沪敖3D】

挑战&#xff1a;考古学家需要一种安全的方法来呈现新出土的陶瓷容器&#xff0c;对比文物形状。 解决方案&#xff1a;Artec Space Spider, Artec Studio 效果&#xff1a;本项目是REVERSEACTION项目的一部分&#xff0c;旨在研究无国家社会中复杂的古代技术。研究团队在考古地…

全国硕士研究生入学考试(考研)常识详解之各类分数线:国家线、院校专业线与自划线

全国硕士研究生入学考试&#xff08;考研&#xff09;常识详解之各类分数线&#xff1a;国家线、院校专业线与自划线 硕士研究生入学考试的分数线是考生能否进入复试、最终被录取的重要参考标准。分数线分为国家线、院校专业线和自划线三类&#xff0c;具体要求根据教育部政策…

Zero Trust 模型:重新定义数字化时代的安全策略

随着云计算、物联网和远程办公的普及&#xff0c;传统的网络边界正在逐渐模糊&#xff0c;安全威胁的形态也在不断演变。面对日益复杂的网络环境&#xff0c;传统的“边界防护”式安全策略显得力不从心。为了应对这一挑战&#xff0c;Zero Trust&#xff08;零信任&#xff09;…

在 Solana 上实现 SOL 转账及构建支付分配器

与以太坊不同&#xff0c;在以太坊中&#xff0c;钱包通过 msg.value 指定交易的一部分并“推送” ETH 到合约&#xff0c;而 Solana 程序则是从钱包“拉取” Solana。 因此&#xff0c;没有“可支付”函数或“msg.value”这样的概念。 下面我们创建了一个新的 anchor 项目&a…