from flask import Blueprint, request, jsonify, session from decorators.login_decorators import login_required from book_from.post_from import CommentFrom from models.book_model import Post, Comment from init.book_init import db from flask import jsonify, request api = Blueprint("comment_api", __name__, url_prefix='/comment') @api.route("/get_comment", methods=['POST']) @login_required def comments(): if request.method != "POST": return jsonify({'code': 400, 'message': '请求错误'}) form = CommentFrom(request.form) if not form.validate(): return jsonify({'code': 400, 'message': '表单数据验证失败'}) user_id = session.get('uuid') post_id = session.get('post_id') if user_id is None: return jsonify({'code': 400, 'message': '用户ID或帖子ID缺失'}) content = form.content.data comment = Comment(content=content, user_id=user_id, post_id=post_id) db.session.add(comment) db.session.commit() return jsonify({'code': 200, 'message': '评论已发送'}) @api.route("/comment_delete/<string:sid>", methods=['DELETE']) @login_required def comment_delete(sid): if request.method != "DELETE": return jsonify({'code': 400, 'message': '请求错误'}) else: comment = sid post = Comment.query.get(comment) if post: db.session.delete(post) db.session.commit() return jsonify({"code": 200, "message": "删除评论成功"}), 200 else: return jsonify({"code": 404, "message": "文章不存在"}), 404
flask---博客后端接口(5. 评论接口实现)
于 2024-05-03 06:57:08 首次发布
文章描述了一个基于Flask的API,用于处理用户评论的创建和删除。它包括了登录验证、表单验证以及数据库操作,展示了如何通过POST和DELETE请求来添加和删除评论。
摘要由CSDN通过智能技术生成