简体   繁体   中英

How to validate html forms in python Flask?

I have a HTML form inside a landing page and I want to send the forms data by ajax to /data rout.
The problem is validating this HTML form in backend.
I know about Flask WTF form but using this method will generate form on backend which is not my case.

from flask import Flask, request, url_for
...
@app.route("/data", methods=["GET", "POST"])
def get_data():
if request.method == "POST":
    username = request.form["username"]
    ...  

My html form:

<form method="POST" action="">
<input type="text" name="username">
<input type="submit" value="Send">
</form>  

One hard way is to validate every field using regex and write several if conditions for them. I'm wondering for easier way?

Using 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)

But as long as you know the format of the incoming data you can still use WTFs for capturing the posted info (you dont need to render WTForms on a page for it to work), for example:

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM