基于Pycharm与数据库的新闻管理系统(3)MongoDB
pip3 install pymongo
1.连接到MongoDB数据库
文件地址:db/mongo_db.py
从 pymongo
模块中导入 MongoClient
类;创建 MongoClient
的一个实例,该实例尝试使用提供的MongoDB连接字符串连接到MongoDB服务器。
from pymongo import MongoClient
client = MongoClient('mongodb://admin:admin123456@localhost:27017')
2.新闻添加
2.1 创建操作类
文件地址:db/mongo_news_dao.py
新闻数据进行交互,并定义了两个方法用于与MongoDB数据库中的新闻数据进行交互。
from db.mongo_db import client
class MongoNewsDao:
#添加函数正文记录
def insert(self,title,content):
try:
client.news.news.insert_one({"title":title,"content":content})
except Exception as e:
print(e)
#查找新闻正文主键
def search_id(self,title):
try:
news = client.news.news.find_one({"title":title})
return str(news["_id"])
except Exception as e:
print(e)
2.2 创建业务类
文件地址:service/news_service.py
处理新闻的添加操作,这个类依赖于 MongoNewsDao
类:
来与 MongoDB 和 MySQL 数据库同时进行交互。
# 导入新闻dao模块
from db.mongo_news_dao import MongoNewsDao
# 创建新闻业务类
class NewsService:
#实例化新闻Dao对象
__mongo_news_dao = MongoNewsDao()
#添加新闻
def insert_news(self,title,editor_id,type_id,👉content👈,is_top):
👉#将添加的新闻写入到mongodb数据库中后
self.__mongo_news_dao.insert(title,content)
#获得新闻id值
content_id = self.__mongo_news_dao.search_id(title)👈
#将新闻信息添加至mysql中
self.__news_dao.insert_news(title, editor_id, type_id, content_id, is_top)
2.3 实现数据库添加操作
实现交互式的Python脚本,用于发表新闻。
这个脚本允许用户输入新闻标题、选择新闻类型、输入新闻内容和置顶级别,并最终提交新闻。
if opt == "1.发表新闻":
os.system("cls")
title = input("\n\t新闻标题")
userid = __user_service.search_userid(username)
result = __type_service.search_list()
for index in range(len(result)):
one = result[index]
print(Fore.LIGHTBLUE_EX, "\n\t%d.%s" % (index + 1, one[1]))
print(Style.RESET_ALL)
opt = input("\n\t类型编号:")
type_id = result[int(opt) - 1][0]
👉# 添加新闻内容
path = input("\n\t输入文件路径:")
file = open(path, "r", encoding="utf-8")
content = file.read()
file.close()👈
is_top = input("\n\t置顶级别(0-5):")
is_commit = input("\n\t是否提交(Y/N):")
if is_commit == 'y' or is_commit == 'Y':
__news_service.insert_news(title, userid, type_id, content, is_top)
print("\n\t保存成功(3秒后自动返回)")
time.sleep(3)
3.新闻更改
3.1 根据新闻id查询新闻内容
from db.mysql_db import pool
class NewsDao:
#根据新闻id查询新闻内容
def search_content_id(self,page):
try:
# 获得连接项
conn = pool.get_connection()
# 获得游标
cursor = conn.cursor()
# 创建sql
sql = """ SELECT content_id FROM t_news where id=%s """
# 执行sql
cursor.execute(sql,[id])
# 获得查询结果
result = cursor.fetchone()[0]
return result
# 返回获得结果
except Exception as e:
print(e)
finally:
if "conn" in dir():
conn.close()
3.2 根据id修改新闻内容
from db.mongo_db import client
from bson.objectid import ObjectId
class MongoNewsDao:
# 根据id修改新闻内容
def update(self, id, title, content):
try:
client.news.news.update_one({"_id":ObjectId(id)},{"$set":{"title":title,"content":content}})
except Exception as e:
print(e)
3.3 更新修改新闻信息
from db.news_dao import NewsDao
from db.redis_news_dao import RedisNewsDao
from db.mongo_news_dao import MongoNewsDao
class NewsService:
#更新修改新闻信息
def update(self,id,title,type_id,👉content,👈is_top):
👉content_id = self.__news_dao.search_content_id(id)
self.__mongo_news_dao.update(content_id,title,content)👈
self.__news_dao.update(id,title,type_id,content_id,is_top)
self.delete_cache(id)#删除缓存中修改的新闻信息
3.4 实现数据库更改操作
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 = 10
👉# 修改新闻正文
path = input("\n\t输入文件路径:")
file = open(path, "r", encoding="utf-8")
content = file.read()
file.close()👈
print("原置顶级别%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,👈 new_is_top)
print("\n\t保存成功(3秒自动返回)")
time.sleep(3)
4. 新闻获取
4.1 根据正文id获取正文信息
文件地址:db/mongo_news_dao.py
from db.mongo_db import client
from bson.objectid import ObjectId
class MongoNewsDao:
#根据正文id获取正文信息
def search_content_by_id(self,id):
try:
news = client.news.news.find_one({"_id":ObjectId(id)})
return news["content"]
except Exception as e:
print(e)
4.2 根据新闻内容id查找新闻内容信息
文件地址:service/news_service.py
from db.mongo_news_dao import MongoNewsDao
class NewsService:
#根据新闻内容id查找新闻内容信息
def search_content_by_id(self,id):
content = self.__mongo_news_dao.search_content_by_id(id)
return content
4.3 实现数据库查询操作
文件地址:app_py.py
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)
# 12.24 新闻缓存
result = __news_service.search_cache(news_id)
title = result[0]
username = result[1]
type = result[2]
content_id = result[3]
# 查询新闻正文👇
# content = "100"
content = __news_service.search_content_by_id(content_id)
is_top = result[4]👆
create_time = str(result[5])
__news_service.cache_news(news_id, title, username, type, content, is_top, create_time)
5.新闻清除
5.1 根据id删除新闻信息
文件地址:db/mongo_news_dao.py
from db.mongo_db import client
from bson.objectid import ObjectId
class MongoNewsDao:
#根据id删除新闻信息
def delete_content_by_id(self,id):
try:
client.news.news.delete_one({"_id":ObjectId(id)})
except Exception as e:
print(e)
5.2 清除新闻
文件地址:service/news_service.py
from db.news_dao import NewsDao
from db.redis_news_dao import RedisNewsDao
from db.mongo_news_dao import MongoNewsDao
class NewsService:
#删除新闻
def delete_news(self,id):
content_id = self.__news_dao.search_content_id(id)
self.__news_dao.delete_by_id(content_id)
self.__news_dao.delete_by_id(id)