經過使用 FlaskForm ,能夠方便快捷的實現表單處理。css
經過使用 flask_wtf 進行表單的相關操做,並完成新用戶合法性註冊。html
pip install flask_wtf
首先,咱們在 todolist
目錄中建立一個 forms.py 文件,定義一個註冊的表單類, 用於完成用戶註冊。示例代碼以下所示:python
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField, PasswordField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError from models import User class RegisterForm(FlaskForm): username = StringField('用戶名:', validators=[ DataRequired(), Length(min=6, max=20)]) email = StringField('郵箱:', validators=[DataRequired(), Email()]) pwd = PasswordField('密碼:', validators=[ DataRequired(), Length(min=8, max=120)]) confirm = PasswordField('確認密碼:', validators=[ DataRequired(), EqualTo('pwd')]) submit = SubmitField('提交') def validate_username(self, username): user = User.query.filter_by(name=username.data).first() if user: raise ValidationError("用戶暱稱已存在。") def validate_email(self, email): user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('郵箱已存在.')
而後修改咱們的路由視圖 todolist\app\views.py
,示例代碼以下所示:mysql
from flask import render_template, redirect, url_for, flash from werkzeug.security import generate_password_hash from app import app, db from forms import RegisterForm from models import User @app.route('/') @app.route('/index') def index(): return render_template('index.html', title="首頁") @app.route('/login') def login(): return render_template('login.html', title='登陸') @app.route('/register', methods=['POST', 'GET']) def register(): form = RegisterForm() if form.validate_on_submit(): username = form.username.data email = form.email.data pwd = form.pwd.data print(username, email, pwd) hash = generate_password_hash(pwd) user = User(name=username, email=email, pwd=pwd) db.session.add(user) db.session.commit() flash('註冊成功', category='info') return redirect(url_for('login')) return render_template('register.html', title='註冊', form=form)
而後,修改 todolist\app\templates\base.html
,添加閃現消息,示例代碼以下所示:sql
<!doctype html> <html lang="en"> <head> {% block head %} <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% block styles %} <!-- Bootstrap CSS --> <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}"> {{ bootstrap.load_css() }} {% endblock %} {% if title %} <title>{{title}}</title> {% else %} <title>願望清單</title> {% endif %} {% endblock %} </head> <body> {% include "nav.html" %} <div class="container"> {% for message in get_flashed_messages() %} <div class="alert alert-primary" role="alert"> {{ message }} </div> {% endfor %} <!-- Your page contont --> {% block content %}{% endblock%} </div> {% block scripts %} <!-- Optional JavaScript --> {{ bootstrap.load_js() }} {% endblock %} </body> </html>
接着,完善 todolist\app\templates\register.html
中的註冊表單,示例代碼以下所示:flask
{% extends 'base.html' %} {% block content %} <h1>註冊頁面</h1> {% from 'bootstrap/form.html' import render_form %} {{ render_form(form) }} {% endblock %}
注:因爲咱們使用了 flask_bootstrap 插件,全部咱們能夠直接經過它來渲染出咱們的表單。bootstrap
最後,因爲表單提交會涉及 跨域訪問問題 CSRF,因此咱們須要修改咱們的 todolist\config.py
文件,添加一個 SECRET_KEY 字段,示例代碼以下所示:跨域
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): SQLALCHEMY_DATABASE_URI = os.environ.get( 'SQLALCHEMY_DATABASE_URI') or 'mysql+pymysql://root:mysql@127.0.0.1:3306/todo' SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = "you will never known it."
此時,當咱們運行起咱們的網站後進入註冊頁面 http://127.0.0.1:5000/register 進行用戶註冊,若是註冊完成後自動跳轉到登錄頁面則表示用戶註冊已經能夠正常運行了。bash