Flask学习:根据WTF实现登录
Posted jumpkin1122
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask学习:根据WTF实现登录相关的知识,希望对你有一定的参考价值。
htm页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <form method="post"> {{form.csrf_token()}} {{form.username.label}}{{form.username}} {{form.password.label}}{{form.password}} {{form.password2.label}}{{form.password2}} {{form.submit}} </form> </body> </html>
Demo02:
from flask import Flask, render_template, request, flash from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, EqualTo app = Flask(__name__) # flash需要加密内容 app.secret_key = "test" class LoginForm(FlaskForm): username = StringField(u"用户名:", validators=[DataRequired()]) password = PasswordField(u"密码:", validators=[DataRequired()]) password2 = PasswordField(u"确认密码:", validators=[DataRequired(), EqualTo("password", "密码不一致")]) submit = SubmitField("提交") @app.route("/", methods=["GET", "POST"]) def login(): login_form = LoginForm() # 1.判断请求方式 if request.method == "POST": # 2.获取请求参数 username = request.form.get("username") password = request.form.get("password") password2 = request.form.get("password2") # 3.验证,通过WTF可以一句话就实现所有的校验 if login_form.validate_on_submit(): print(username, password, password2) return "登录成功" else: flash("参数有误") return render_template("login.html", form=login_form) # 4.启动程序 if __name__ == ‘__main__‘: app.run()
测试效果:
以上是关于Flask学习:根据WTF实现登录的主要内容,如果未能解决你的问题,请参考以下文章
Flask 插件学习:Flask-WTF 和 WTForms 扩展