Flask-表單登陸

1、目標:

  使用Flask框架,編寫一個頁面。該頁面判斷用戶提交的用戶名和密碼是否爲lethons和123456,若是是則跳轉到百度首頁,不然返回錯誤信息。html

2、代碼:

一、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()

二、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>

3、總結

一、使用wtforms模塊,須要定義一個繼承Form的類;類中定義了所須要的表單類型flask

二、在視圖函數中須要定義一個form對象,並將其傳入HTML模中app

三、使用.data方法來獲得頁面傳來的參數框架

四、在HTML頁面中,使用{{form.username}}來替代<input>標籤函數

相關文章
相關標籤/搜索