Flask web模板五–注册和登录

通过使用wtform和Flask-wtf分别完成注册和登录功能,使用wtform创建一个用户注册的表单类,再用Flask-wtf创建一个用户登录的表单类。

1、创建用户注册表单类
在app/forms目录下创建account.py内容如下

# -*- coding:utf-8 -*-
from wtforms import Form, StringField, IntegerField, PasswordField, SubmitField
from wtforms.validators import Length, NumberRange, DataRequired, Email, ValidationError, EqualTo
from app.models.user import User
from flask_wtf import FlaskForm


# 这里使用wtforms类来创建注册的类
class RegisterForm(Form):
    email = StringField(
        validators=[
            DataRequired(),
            Length(8, 64),
            Email(message='电子邮箱不符合规范')
        ],
        render_kw={
            'placeholder': '请输入电子邮件!'
        }
    )
    password = PasswordField(
        validators=[
            DataRequired(message='密码不可以为空,请输入你的密码'),
            Length(6, 32, message='密码最小6位最长32')
        ],
        render_kw={
            'placeholder': '请输入密码!'
        }
    )
    password2 = PasswordField(
        validators=[
            DataRequired(message='密码不能为空,请输入你的密码'),
            Length(6, 32, message='密码最小6位最长32'),
            EqualTo('password', message="两次密码不一致!")
        ],
        render_kw={
            'placeholder': '请确认密码!'
        }
    )
    nickname = StringField(
        validators=[
            DataRequired(),
            Length(2, 10, message='昵称至少需要2个字符,最多10个字符')
        ],
        render_kw={
            'placeholder': '请输入昵称!'
        }
    )
    submit = SubmitField(
        '提交'
    )

    # 判断数据库中是否有同名的email
    # 这里的field是wtform自动传入的,是客户端浏览器传入的参数
    # wtform 会自动检测 validate_email这个函数将这个函数和email属性做关联
    def validate_email(self, field):
        # 不论查询出多少条,都只返回1条
        if User.query.filter_by(email=field.data).first():
            raise ValidationError("电子邮件已被注册")

    def validate_nickname(self, field):
        if User.query.filter_by(nickname=field.data).first():
            raise ValidationError('昵称已存在')


# 这里使用Flask-WTF包来创建登录验证的类
# class LoginForm(Form):
class LoginForm(FlaskForm):
    email = StringField(
        validators=[
            DataRequired(),
            Length(8, 64),
            Email(message='电子邮箱不符合规范')
        ],
        render_kw={
            'placeholder': '请输入注册邮箱!'
        }
    )
    password = PasswordField(
        validators=[
            DataRequired(message='密码不可以为空,请输入你的密码'),
            Length(6, 32, message='密码长度是6到32位')
        ],
        render_kw={
            'placeholder': '请输入密码!'
        }
    )
    submit = SubmitField('提交')

2、创建注册视图函数
在app/web/account.py中添加如下代码

# -*- coding:utf-8 -*-
# 视图函数定义文件,和账号相关的视图函数

from .blueprint import web
from flask import request, render_template, redirect, session, url_for, flash
from app.forms.account import RegisterForm, LoginForm
from app.models.base import db
from app.models.user import User


# 注册视图函数
@web.route('/register/', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        with db.auto_commit():
            user = User()
            user.set_attrs(form.data)
            db.session.add(user)
        return redirect(url_for('web.login'))
        # user.password = generate_password_hash(form.password.data)
    return render_template('register.html', form=form)


# 登录视图函数
@web.route('/login/', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if request.method == 'POST' and form.validate():
        user = User.query.filter_by(email=form.email.data).first()
        if user and user.check_password(form.password.data):
            return redirect(url_for('web.personal'))
        else:
            flash('账号不存在或者密码错误')
    return render_template('login.html', form=form)


# 登录后个人中心视图函数
@web.route('/personal/', methods=['GET'])
def personal():
    pass

3、创建模板文件
在app/templates下创建login.html内容如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
    <h1>用户登录</h1>
    {% with messages = get_flashed_messages() %}
        {% for message in messages %}
            {% if message %}
                <div class="alert alert-warning" role="alert">{{ message }}</div>
            {% endif %}
        {% endfor %}
    {% endwith %}
    <form method="post" action="">
        <div>{{ form.email }}</div>
        {% for msg in form.email.errors %}
            <small class="errors">{{ msg }}</small><br>
        {% endfor %}
        <div>{{ form.password }}</div>
        {% for msg in form.password.errors %}
            <small class="errors">{{ msg }}</small><br>
        {% endfor %}
        <div>{{ form.submit }}</div>
        {{ form.csrf_token }}
    </form>
</body>
</html>

创建注册视图函数rigister.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
    <h1>用户注册</h1>
    <form method="post" action="">
        <div>{{ form.nickname }}</div>
        <div>{{ form.email }}</div>
        <div>{{ form.password }}</div>
        <div>{{ form.password2 }}</div>
        <div>{{ form.submit }}</div>
        {{ form.csrf_token }}
    </form>
</body>
</html>

 

发表评论