v-borutkin
2/17/2019 - 3:22 PM

flask - validate form

from flask import Flask, request
from flask_wtf import FlaskForm
from wtforms import StringField, validators
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)
app.config.update( 
    DEBUG=True,
    SECRET_KEY='this must key',
    WTF_CSRF_ENABLED=False
)

class ContactForm(FlaskForm):
    name = StringField(label='name', validators=[validators.length(min=4, max=25)])
    email = StringField(label='email', validators=[validators.length(min=4, max=25), validators.Email()])


@app.route("/", methods=['GET', 'POST'])
def hello_world():


    if request.method == 'GET':
        return "Hello World!", 200
    if request.method == 'POST':
        print(request.form)
        form = ContactForm(request.form)

        if form.validate():
            return ('valid', 200)
        else:
            return ('invalid', 400)


if __name__ == '__main__':
    app.run()