我正在使用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"
我出错的任何想法?
答案 0 :(得分:0)
您应该使用request.form
代替request.data
,如https://stackoverflow.com/a/16664376/1182891
修改强> 我的意思是在响应中,而不是表单构造函数
if not form.validate_on_submit():
return jsonify({'test': request.form})