Python之Flask-wtforms

该博客展示了使用Flask框架实现登录表单的代码。通过导入相关模块,创建表单类进行字段定义和校验规则设置。在路由函数中,根据请求方法生成HTML或对用户提交的数据进行验证,若验证通过则输出正确信息,否则输出错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from flask import Flask, render_template, request, redirect
from wtforms import Form
from wtforms import validators
from wtforms.fields import simple
from wtforms import widgets

app = Flask(__name__, template_folder='templates')
app.debug = True

"""
1.生成html
2.对用户的请求进行校验
"""


class LoginForm(Form):
    # 字段
    name = simple.StringField(
        label='用户名',
        validators=[
            validators.DataRequried(message='用户名不能为空'),
            validators.length(min=6, max=18, message="")
        ],
        widget=widgets.TextInput(),  # 页面上显示的插件
    )
    pwd = simple.PasswordField(
        label='密码',
        validators=[
            validators.DataRequried(message='用户名不能为空'),
            validators.length(min=6, max=18, message=""),
            validators
        ],
        widget=widgets.PasswordInput(),
    )


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        form = LoginForm()  # 生成html
        return render_template('login.html', form=form)
    else:
        form = LoginForm(formdata=request.form)  # 获取提交的数据,并进行验证
        if form.validate():
            print("用户提交的数据正确:", form.data)
        else:
            print(form.errors)
        return render_template('login.html', form=form)


@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    # 请求进来的时候,执行的是Call方法
    app.__call__
    app.run()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值