天天看点

Python编程:Flask表单扩展Flask-WTF代码示例

表单扩展  Flask

-WTF

文档: 

https://flask-wtf.readthedocs.io/en/stable/ 安装

pip install Flask-WTF      

可以进行csrf验证

代码示例

1、定义模型类 视图使用

from flask import (
    Flask,
    render_template,
    session,
    url_for,
    redirect
)

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, EqualTo

app = Flask(__name__)

app.secret_key = "1231safdasdf"


class RegisterForm(FlaskForm):
    #                         标签           验证器
    user_name = StringField(label="用户名", validators=[DataRequired("用户名不能为空")])
    password = PasswordField(label="密码", validators=[DataRequired("密码不能为空")])
    re_password = PasswordField(label="密码", validators=[DataRequired("密码不能为空"),
                                                        EqualTo("password", "两次密码不一致")])
    submit = SubmitField(label="提交")


@app.route("/register", methods=["GET", "POST"])
def register():
    # 如果是POST提交,前端数据会放到form对象中
    form = RegisterForm()

    # 验证数据,验证合格后再进行操作
    if form.validate_on_submit():
        username = form.user_name.data
        pwd = form.password.data
        re_pwd = form.re_password.data
        session["user_name"] = username
        return redirect(url_for("index"))

    return render_template("register.html", form=form)


@app.route("/")
def index():
    username = session.get("user_name")
    return "注册成功:username: {}".format(username)


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

2、模板使用

<form action="" method="POST">
    {{ form.csrf_token }}

    {{ form.user_name.label }}
    <p>{{ form.user_name }}</p>
    {% for msg in form.user_name.errors %}
    <p>{{ msg }}</p>
    {% endfor %}

    {{ form.password.label }}
    <p>{{ form.password }}</p>
    {% for msg in form.password.errors %}
    <p>{{ msg }}</p>
    {% endfor %}

    {{ form.re_password.label }}
    <p>{{ form.re_password }}</p>
    {% for msg in form.re_password.errors %}
    <p>{{ msg }}</p>
    {% endfor %}

    {{ form.submit }}
</form>      

渲染效果

Python编程:Flask表单扩展Flask-WTF代码示例