flask学习二 :表单

模块: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 ,代码如下:




    
    首页


    

PS:CSRF已经在html中设置完毕{{form.csrf_token}}。需要注意的是,必须在将csrf的配置加载到APP中:

from flask_wtf import CSRFProtect

csrf = CSRFProtect()

工厂函数中加入:    

csrf.init_app(app)


你可能感兴趣的:(flask基础)