创新设计记录-7:论坛
界面展示
所有的用户共享一个论坛,可以看到所有用户的博客。
点击某个博客的标题,会跳转到对应的博客界面
**
**
功能实现:
后端:
def get_all_blogs() -> BaseResponse:
"""
获取论坛上所有的博客列表
"""
try:
with Session(engine) as session:
# 按时间降序排列
# 需要添加博客的作者信息
res = session.query(Blog.id, Blog.title, Blog.content, Blog.create_time, User.id, User.name).join(User,
User.id == Blog.user_id).order_by(
Blog.create_time.desc()).all()
except Exception as e:
print(e)
return BaseResponse(code=500, message=str(e))
return BaseResponse(code=200, msg='success', data=[blog_user_to_dict(b) for b in res])
获取所有的博客列表
def add_comment(comment: CommentModel) -> BaseResponse:
comment_id = uuid.uuid4().hex
now = datetime.datetime.now()
try:
with Session(engine) as session:
session.add(Comment(id=comment_id,
content=comment.comment,
create_time=now,
user_id=comment.user_id,
blog_id=comment.blog_id))
session.commit()
return BaseResponse(code=200, msg='success', data={comment_id: comment_id})
except Exception as e:
print(e)
return BaseResponse(code=500, message=str(e))
评论功能
def get_comment(blog_id: str) -> BaseResponse:
"""
获取一个博客的评论
"""
try:
with Session(engine) as session:
res = session.query(Comment, User.name).join(User, Comment.user_id == User.id).filter(
Comment.blog_id == blog_id).all()
except Exception as e:
print(e)
return BaseResponse(code=500, message=str(e))
return BaseResponse(code=200, msg='success',
data={'comment_list': [serialize_comment_user(comment) for comment in res]})
获取一个博客的所有评论
def delete_comment(comment_id: str, blog_id: str, user_id: str) -> BaseResponse:
"""
删除博客的评论,注意权限判断
"""
try:
with Session(engine) as session:
res = session.query(Comment).filter(Comment.id == comment_id).first()
if res is None:
return BaseResponse(code=400, msg='没有这个评论')
if res.user_id == user_id: # 删除者是评论本人
session.delete(res)
session.commit()
return BaseResponse(code=200, msg='success')
blog = session.query(Blog).filter(Blog.id == blog_id).first()
if blog.user_id == user_id: # 删除者是博客作者
session.delete(res)
session.commit()
return BaseResponse(code=200, msg='success')
return BaseResponse(code=400, msg='你没有删除的权限')
except Exception as e:
print(e)
return BaseResponse(code=500, msg=str(e))
删除一个博客的评论,这里加了角色验证,只有评论者本人,文章的作者才可以删除评论,否则不允许删除评论
[