Flask的WTforms

一、简单介绍

WTForms是一个支持多个web框架的form组件,主要用于对用户请求数据进行验证。

类似于Django中的modelform

安装:

pip3 install wtforms

二、简单使用

 后端代码app.py

from flask import Flask, request, render_template, session
from flask_session import Session
from redis import Redis
from wtforms import Form, validators, widgets
from wtforms.fields import simple, core

app = Flask(__name__)
app.config["DEBUG"] = True
# 用原生的session要设置SECRET_KEY
# app.config["SECRET_KEY"] = 'uihuiwuiwoiw'

# 使用redis session
app.config["SESSION_TYPE"] = "redis"
# 实例化redis
app.config["SESSION_REDIS"] = Redis(host="127.0.0.1", port=6379) # redis 不要放在公网

# 设置存在客户端的cookies中的session的名字
# app.config["SESSION_COOKIE_NAME"] = "#¥%……&*(#E$RTY$%RTY%^Y&U%^&*"

# 用第三方session替换原生的session;这是基于原生的session的
Session(app)


class LoginForm(Form):
    username = simple.StringField(
        label="用户名",
        validators=[
            validators.DataRequired(message="用户名不能为空"),
            validators.Length(min=4, max=8, message="用户名必须大于等于4,小于等于8")
        ]
    )
    password = simple.PasswordField(
        label="密码",
        validators=[
            validators.DataRequired(message="密码不能为空"),
            validators.Length(min=4, max=8, message="密码必须大于等于4,小于等于8")
        ])


@app.route('/login',methods=['GET','POST'])
def login():
    login_form = LoginForm()
    if request.method == "GET":
        return render_template('login.html', lf=login_form)
    else:
        login_form_data = LoginForm(request.form)
        if login_form_data.validate():
            session['user'] = login_form_data.data.get('username')
            return str(session["user"])
        else:
            return render_template("login.html", lf=login_form_data)


class RegForm(Form):
    username = simple.StringField(
        label="用户名",
        validators=[
            validators.DataRequired(message="用户名不能为空"),
        ]
    )
    password = simple.PasswordField(
        label="密码",
        validators=[
            validators.DataRequired(message="密码不能为空"),
            validators.Length(min=6, max=16, message="密码必须大于等于6,小于等于16")
        ])
    repassword = simple.PasswordField(
        label="确认密码",
        validators=[
            validators.EqualTo("password", message="两次密码不一致")
        ]
    )
    gender = core.SelectField(
        label="性别",
        choices=(
            (1, ""),
            (2, "")
        ),
        default=1,
        # widget=widgets.RadioInput(),
        # render_kw={"class": "my_class"},
        coerce=int
    )
    email = simple.StringField(
        label="邮箱",
        validators=[
            validators.DataRequired(message="邮箱不能为空"),
            validators.Email(message="不符合规定")
        ]
    )
    hobby = core.SelectMultipleField(
        label="癖好",
        choices=(
            (1, "萝莉"),
            (2, "御姐"),
            (3, "小哥哥"),
            (4, "正太")
        ),
        # widget=widgets.,
        coerce=int,
        default=(1, 4)
    )


@app.route('/reg', methods=['GET', 'POST'])
def reg():
    if request.method == "GET":
        rf = RegForm()
        return render_template("reg.html", rf=rf)
    else:
        rf_data = RegForm(request.form)
        if rf_data.validate():
            print(rf_data.data.get("hobby"))
            print(type(rf_data.data.get("gender")))
            return "注册成功"
        else:
            return render_template("reg.html", rf=rf_data)


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

登录模板:login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" novalidate>
    <p>{{ lf.username.label }}:{{ lf.username }}{{ lf.username.errors.0 }}</p>
    <p>{{ lf.password.label }}:{{ lf.password }}{{ lf.password.errors[0] }}</p>
    <input type="submit" value="登录">
</form>
</body>
</html>

模板中也可以直接循环获取模板数据如下的注册页面

注册模板:reg.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style></style>
</head>

<body>
<form action="" method="post" novalidate>
    {% for field in rf %}
        <p>{{ field.label }}{{ field }} <span style="color: red">{{ field.errors.0 }}</span></p>
    {% endfor %}
    <input type="submit" value="注册">

</form>
</body>
</html>

 

posted @ 2019-03-01 17:12  清风_Z  阅读(223)  评论(0编辑  收藏  举报