Flask-WTF 验证总是失败

Flask-WTF validation always failing

我正在使用 Flask-WTF 进行表单验证,但验证总是失败。

app.py

from flask import Flask
from flask import request
from flask import jsonify

app = Flask(__name__)

@app.route('/add', methods=['POST'])
def add_survey_entry():

    form = Survey_Form(csrf_enabled=False)

    if not form.validate_on_submit():
        return jsonify({'test': request.data})

Survey_Form.py

from flask_wtf import Form
from wtforms import TextAreaField
from wtforms import validators
from wtforms import StringField
from wtforms import IntegerField
from wtforms import RadioField

class Survey_Form(Form):

    name = StringField('name', validators=[
        validators.optional(),
        validators.Length(min=3, max=50)
    ])

    age = IntegerField('age', validators=[
        validators.required(),
        validators.number_range(min=18, max=99)
    ])

    message = TextAreaField('message', validators=[
        validators.optional(),
        validators.length(max=500)
    ])

当我向 http://example.com/add 提交 POST 请求时,它总是失败并且 request.data 为空。我使用以下请求:

curl http://127.0.0.1:5000/add -d "name=Bob&age=19&message=I+am+a+test+message"

我哪里出错了?

您应该使用 request.form 而不是 request.data,如

中所述

编辑 我的意思是在响应中,而不是表单构造函数

if not form.validate_on_submit():
    return jsonify({'test': request.form})