flask---博客后端接口(5. 评论接口实现)

文章描述了一个基于Flask的API,用于处理用户评论的创建和删除。它包括了登录验证、表单验证以及数据库操作,展示了如何通过POST和DELETE请求来添加和删除评论。
摘要由CSDN通过智能技术生成
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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值