使用Flask框架,编写一个页面。该页面判断用户提交的用户名和密码是否为lethons和123456,若是是则跳转到百度首页,不然返回错误信息。html
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()
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>
一、使用wtforms模块,须要定义一个继承Form的类;类中定义了所须要的表单类型flask
二、在视图函数中须要定义一个form对象,并将其传入HTML模中app
三、使用.data方法来获得页面传来的参数框架
四、在HTML页面中,使用{{form.username}}来替代<input>标签函数