赞
踩
这篇文章讲两种表单提交方式,先说一下目录树,下图左侧
templates文件夹放置html文件,
static文件夹放置css,js文件.
首先在templates文件夹新建一个login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div align="center">
<h2>User Management</h2>
{% if message %} {{message}} {% endif %}
<form method="POST">
<input type="text" name="username" placeholder="username">
<br>
<input type="password" name="password" placeholder="password">
<br>
<input type="submit" value="Submit">
<input type="reset" value="reset">
</form>
</div>
</body>
</html>
{% if message %} {{message}} {% endif %}用于输出登录失败时的错误信息,在form标签中添加提交方式<form method="POST">
然后新建一个login.py
from flask import Flask,request,render_template,redirect
app = Flask(__name__)
//绑定访问地址127.0.0.1:5000/user
@app.route("/user",methods=['GET','POST'])
def login():
if request.method =='POST':
username = request.form['username']
password = request.form['password']
if username =="user" and password=="password":
return redirect("http://www.baidu.com")
else:
message = "Failed Login"
return render_template('login1.html',message=message)
return render_template('login1.html')
if __name__ == '__main__':
app.run(debug=True)
这里对上面login1.html和login.py修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div align="center">
<h2>User Management</h2>
{% if message %} {{message}} {% endif %}
<form method="POST">
username:{{form.username}}
<br>
password:{{form.password}}
<br>
<input type="submit" value="Submit">
<input type="reset" value="reset">
</form>
</div>
</body>
</html>
这里直接去掉了输入的input标签,换成了
username:{{form.username}},
password:{{form.password}} (jinja2模板)
from flask import Flask,request,render_template,redirect
app = Flask(__name__)
from wtforms import Form,TextField,PasswordField,validators
class LoginForm(Form):
username = TextField("username",[validators.Required()])
password = PasswordField("password",[validators.Required()])
@app.route("/user",methods=['GET','POST'])
def login():
myForm = LoginForm(request.form)
if request.method =='POST':
if myForm.username.data =="user" and myForm.password.data=="password" and myForm.validate():
return redirect("http://www.baidu.com")
else:
message = "Failed Login"
return render_template('login1.html',message=message,form=myForm)
return render_template('login1.html',form=myForm)
if __name__ == '__main__':
app.run(debug=True)
(1)from wtforms import Form,TextField,PasswordField,validators
从wtforms 导入Form类,所有自定义的表单都需要继承这个类,比如
class LoginForm(Form):
(2)一系列的Field对应html的input标签控件,validators是验证器,用于验证用户输入的数据.
myForm.password.data
以上代码用于获取用户输入的密码,这里验证中多了myForm.validate():
(3)创建一个对象,[validators.Required()]表明这个值必须要输入
username = TextField("username",[validators.Required()])
(4)在最后还需将myForm传入form
return render_template('login1.html',form=myForm)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。