蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

验证不同字段并处理两类拒绝

PYTHONWindows、CPython 3.12.14、Flask 3.1.3、Flask-Login 0.6.3、Flask-WTF 1.3.0、WTForms 3.2.1、SQLite 3.53.1forms.py
forms.py95 行
from flask import redirect, render_template, url_for
from flask_login import current_user, login_required
from flask_wtf import FlaskForm
from wtforms import BooleanField, EmailField, PasswordField, SelectField, StringField, SubmitField, TextAreaField
from wtforms.validators import DataRequired, Email, EqualTo, Length, Optional, ValidationError

from .accounts import Member, accounts, finish_login, lookup, normalize_email, normalize_username, save_member, valid_username


def clean(value):
    return normalize_username(value or "")


def trim(value):
    return (value or "").strip()


class Registration(FlaskForm):
    username = StringField("用户名",filters=[clean],
                           validators=[DataRequired(message="请填写用户名。"),
                                       Length(min=3,max=32,message="用户名须为 3 到 32 个字符。")])
    email = EmailField("邮箱",filters=[trim],
                       validators=[DataRequired(message="请填写邮箱。"),
                                   Email(check_deliverability=False,message="请输入有效邮箱。")])
    password = PasswordField("口令",validators=[DataRequired(message="请填写口令。"),
                                            Length(min=8,max=128,message="口令须为 8 到 128 个字符。")])
    confirmation = PasswordField("确认口令",validators=[
        DataRequired(message="请再次输入口令。"),EqualTo("password",message="两次口令不一致。")])
    submit = SubmitField("提交表单注册")

    def validate_username(self,field):
        if not valid_username(field.data):
            raise ValidationError("用户名含有不允许的字符。")
        if lookup(Member.username,field.data):
            raise ValidationError("用户名已使用。")

    def validate_email(self,field):
        if field.errors:
            return
        field.data = normalize_email(field.data)
        if lookup(Member.email,field.data):
            raise ValidationError("邮箱已使用。")


class SignIn(FlaskForm):
    username = StringField("用户名",filters=[clean],validators=[DataRequired(),Length(min=3,max=32)])
    password = PasswordField("口令",validators=[DataRequired(),Length(max=128)])
    remember = BooleanField("记住我")
    submit = SubmitField("提交表单登录")


class Preferences(FlaskForm):
    note = TextAreaField("可选观测备注",filters=[trim],
                         validators=[Optional(),Length(min=3,max=40,message="备注须为 3 到 40 个字符。")])
    shore = SelectField("关注岸段",choices=[("north","北岸"),("south","南岸")],
                        validate_choice=True)
    updates = BooleanField("接收练习更新")
    submit = SubmitField("验证偏好")


@accounts.route("/register",methods=["GET","POST"])
def register_wtf():
    if current_user.is_authenticated:
        return redirect(url_for("accounts.profile"))
    form = Registration()
    if form.validate_on_submit():
        member = save_member(form.username.data,form.email.data,form.password.data)
        if member is not None:
            return finish_login(member)
        form.username.errors.append("用户名或邮箱已使用。")
    return render_template("account-wtf.html",title="WTForms 注册",form=form),422 if form.errors else 200


@accounts.route("/login",methods=["GET","POST"])
def login_wtf():
    if current_user.is_authenticated:
        return redirect(url_for("accounts.profile"))
    form = SignIn()
    if form.validate_on_submit():
        member = lookup(Member.username,form.username.data) if valid_username(form.username.data) else None
        if member is not None and member.is_active and member.check_password(form.password.data):
            return finish_login(member,form.remember.data)
        form.username.errors.append("用户名或口令错误。")
    return render_template("account-wtf.html",title="WTForms 登录",form=form),422 if form.errors else 200


@accounts.route("/preferences",methods=["GET","POST"])
@login_required
def preferences():
    form = Preferences()
    if form.validate_on_submit():
        return render_template("account-wtf.html",title="偏好字段",form=form,
            result={"note":form.note.data,"shore":form.shore.data,"updates":form.updates.data})
    return render_template("account-wtf.html",title="偏好字段",form=form),422 if form.errors else 200
本例需在 Windows、CPython 3.12.14、Flask 3.1.3、Flask-Login 0.6.3、Flask-WTF 1.3.0、WTForms 3.2.1、SQLite 3.53.1 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、CPython 3.12.14、Flask 3.1.3、Flask-Login 0.6.3、Flask-WTF 1.3.0、WTForms 3.2.1、SQLite 3.53.1

入口文件:projects/flask-coast-accounts/coast_blog/forms.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 forms.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、CPython 3.12.14、Flask 3.1.3、Flask-Login 0.6.3、Flask-WTF 1.3.0、WTForms 3.2.1、SQLite 3.53.1。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Flask

课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202611a483.zip

下载课程关联工程包:Flask

课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202611a482.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习