模块:flask-wtf
创建表单 form.py ,代码如下:
# -*- coding: utf-8 -*-
from flask_wtf import FlaskForm # FlaskForm基本表单
from wtforms import StringField, PasswordField # HTML标准字段
from wtforms.validators import Length, DataRequired # 验证方式
# 测试验证表单
class ExampleForm(FlaskForm):
name = StringField('name', validators=[DataRequired(message=u"用户名不能为空"), Length(3, 10, message=u'长度位于3~10之间')], render_kw={'placeholder': u'输入用户名'})
password = PasswordField('password', validators=[DataRequired(message=u"密码不能为空"), Length(3, 10, message=u'长度位于3~10之间')], render_kw={'placeholder': u'输入密码'})
创建表单 urls.py ,代码如下:
# -*- coding: utf-8 -*-
from .views import *
# 统一管理注册路由,关联试图
home.add_url_rule('/', view_func=ExampleView.as_view('example'))
创建表单 views.py ,代码如下:
# -*- coding: utf-8 -*-
from flask import render_template, Blueprint, flash
from flask.views import MethodView
from app.form import ExampleForm
home = Blueprint('home', __name__)
# 继承MethodView
class ExampleView(MethodView):
def __init__(self):
super(ExampleView, self).__init__()
self.example_form = ExampleForm()
def get(self):
return render_template('home/index.html', form=self.example_form)
def post(self):
if not self.example_form.validate_on_submit():
flash(self.example_form.name.data + '|' + self.example_form.password.data)
return render_template('home/index.html', form=self.example_form)
print(self.example_form.name.data, self.example_form.password.data)
# 这里返回原来的页面,是为了页面上查看crfs_token是否生效
return render_template('home/index.html', form=self.example_form)
创建表单 index.html ,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<div class="base_login">
<h1>用户登录</h1>
<div>
<form method="POST">
<!--启动CSRF-->
{{form.csrf_token}}
<p>
用户:{{form.name(size=20,id='name')}}
{%for e in form.name.errors%}
<span style="color: red">*{{e}}</span>
{%endfor%}
</p>
<p>
密码:{{form.password(size=20,id='password')}}
{%for e in form.password.errors%}
<span style="color: red">*{{e}}</span>
{%endfor%}
</p>
<p><button style="float: right" type="submit">登录</button></p>
</form>
</div>
</div>
</body>
</html>
PS:CSRF已经在html中设置完毕{{form.csrf_token}}。需要注意的是,必须在将csrf的配置加载到APP中:
from flask_wtf import CSRFProtect
csrf = CSRFProtect()
工厂函数中加入:
csrf.init_app(app)