我在登陆页面中有一个 HTML 表单,我想通过 ajax 将表单数据发送到/data rout。
问题是在后端验证此 HTML 表单。
我知道 Flask WTF 表单,但使用此方法会在后端生成表单,这不是我的情况。
from flask import Flask, request, url_for
...
@app.route("/data", methods=["GET", "POST"])
def get_data():
if request.method == "POST":
username = request.form["username"]
...
我的 html 表单:
<form method="POST" action="">
<input type="text" name="username">
<input type="submit" value="Send">
</form>
一种困难的方法是使用正则表达式验证每个字段并为它们编写几个 if 条件。我想知道更简单的方法吗?
使用 Webargs
from webargs import flaskparser, fields
FORM_ARGS = {
'email': fields.Email(required=True),
'username': fields.Str(required=True),
@app.route("/data", methods=["GET", "POST"])
def get_data():
if request.method == "POST":
parsed_args = flaskparser.parser.parse(FORM_ARGS, request)
但只要您知道传入数据的格式,您仍然可以使用 WTF 来捕获发布的信息(您不需要在页面上呈现 WTForms 即可工作),例如:
# import blurb
class Form(FlaskForm):
username = StringField('Username', validators=[InputRequired()])
email = EmailField('Email', validators=[InputRequired(), Length(4, 128), Email()])
@app.route("/data", methods=["GET", "POST"])
def get_data():
if request.method == "POST":
form = Form() # will register fields called 'username' and 'email'.
if form.validate_on_submit():
# do something
我是一名优秀的程序员,十分优秀!