gpt4 book ai didi

python - 如何在 python Flask 中验证 html 表单?

转载 作者:太空宇宙 更新时间:2023-11-04 11:22:02 24 4
gpt4 key购买 nike

我在登陆页面中有一个 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

关于python - 如何在 python Flask 中验证 html 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55772012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com