使用表单数据进行发布请求时出现 KeyError

问题描述

我正在尝试发出 POST 请求以在用户帖子上创建评论。我相信我已经正确地完成了所有事情,所以这可能是一个愚蠢的错误,但出于某种原因,对于我试图从表单数据中获取的每个值,我都收到了 TypeError。

这是我的 POST 评论路线:

@comment_routes.route('<int:id>/new',methods=["POST"])
def new_comment(id):
    form = CommentForm()
    post = User_Post.query.get(id)
    if form.validate_on_submit():
        comment = Comment(
            post_id=id,user_id=form.data['user_id'],content=form.data['content']
        )
        db.session.add(comment)
        db.session.commit()
        return comment.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}

和我的 FlaskForm:

from flask_wtf import FlaskForm
from wtforms import StringField,IntegerField
from wtforms.validators import Datarequired
from app.models import User


class CommentForm(FlaskForm):
    user_id: IntegerField('user_id',validators=[Datarequired()])
    post_id: IntegerField('post_id',validators=[Datarequired()])
    content: StringField('content',validators=[Datarequired()])

我正在使用 json 在邮递员中进行 POST 调用。这种方式适用于我的 post_route,但由于某种原因,我的 comment_route 出现了类型错误

错误

KeyError: 'user_id' // Werkzeug Debugger

我认为这是从我对邮递员的帖子请求中解析我的表单数据的方式的问题。我将数据作为 json 发送,但这在过去并没有给我带来问题。为了安全起见,我确实将 content-type 切换为 form-data 并以这种方式传递它,但仍然出现相同的错误。这是我对邮递员所做的伪代码

POST http://localhost:3000/api/comments/1/new 
headers: {
    Content-Type: application/json,X-CSrftoken: (....)
}
body: {
    "user_id": 1,"content": "testing"
}

和我的评论模型供参考:

class Comment(Base):
    __tablename__ = "comments"
    query = Session.query_property()

    id = db.Column(db.Integer,primary_key=True)
    content = db.Column(db.String(1000),nullable=False)
    user_id = db.Column(db.Integer,db.ForeignKey('users.id'))
    post_id = db.Column(db.Integer,db.ForeignKey('users_posts.id'))

    def to_dict(self):
        return {
            'id': self.id,'content': self.content,'user_id': self.user_id,'post_id': self.post_id,}

    def to_dict_full(self):
        return {
            'id': self.id,'liked_by': [user.to_dict() for user in self.liked_by]
        }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)