Flask-表单登录

一、目标:

  使用Flask框架,编写一个页面。该页面判断用户提交的用户名和密码是否为lethons和123456,如果是则跳转到百度首页,否则返回错误信息。

二、代码:

1、Flask app

 1 # main.py
 2 from flask import Flask, request, redirect, render_template
 3 from wtforms import Form, TextField, PasswordField, validators
 4 
 5 
 6 app = Flask(__name__)
 7 
 8 
 9 class LoginForm(Form):
10     username = TextField("username", [validators.required()])
11     password = PasswordField("password", [validators.required()])
12 
13 
14 @app.route('/user', methods=['GET', 'POST'])
15 def login():
16     myForm = LoginForm(request.form)
17     if request.method == 'POST':
18         if myForm.username.data == 'jikexueyuan' and myForm.password.data == '123456':
19             return redirect('https:www.baidu.com')
20         else:
21             message = 'Login Failed'
22             return render_template('index.html', message=message, form=myForm)
23     return render_template('index.html', form=myForm)
24 
25 
26 if __name__ == "__main__":
27     app.run()

2、HTML模板文件

 1 # index.html
 2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>Document</title>
 9 </head>
10 <body>
11     <div align="center">
12         <h1>User Management</h1>
13         {% if message %}
14             {{ message }}
15         {% endif %}
16         <form method="POST">
17             username: {{form.username}}
18             <br>
19             password: {{form.password}}
20             <br>
21             <input type="submit" value="submit">
22             <input type="reset" value="reset">
23         </form>
24     </div>
25 </body>
26 </html>

三、总结

1、使用wtforms模块,需要定义一个继承Form的类;类中定义了所需要的表单类型

2、在视图函数中需要定义一个form对象,并将其传入HTML模中

3、使用.data方法来得到页面传来的参数

4、在HTML页面中,使用{{form.username}}来替代<input>标签

猜你喜欢

转载自www.cnblogs.com/Lethons/p/9156221.html