Python Flask-表单提交方式
這篇文章講兩種表單提交方式,先說一下目錄樹,下圖左側(cè)
templates文件夾放置html文件,
static文件夾放置css,js文件.
1.請(qǐng)求上下文
首先在templates文件夾新建一個(gè)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 %}用于輸出登錄失敗時(shí)的錯(cuò)誤信息,在form標(biāo)簽中添加提交方式<form method="POST">
然后新建一個(gè)login.py
from flask import Flask,request,render_template,redirectapp = 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)2.WTForm
這里對(duì)上面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標(biāo)簽,換成了
username:{{form.username}},
password:{{form.password}} (jinja2模板)
(1)from wtforms import Form,TextField,PasswordField,validators
從wtforms 導(dǎo)入Form類,所有自定義的表單都需要繼承這個(gè)類,比如
(2)一系列的Field對(duì)應(yīng)html的input標(biāo)簽控件,validators是驗(yàn)證器,用于驗(yàn)證用戶輸入的數(shù)據(jù).
myForm.password.data以上代碼用于獲取用戶輸入的密碼,這里驗(yàn)證中多了myForm.validate():
(3)創(chuàng)建一個(gè)對(duì)象,[validators.Required()]表明這個(gè)值必須要輸入
username = TextField("username",[validators.Required()])(4)在最后還需將myForm傳入form
return render_template('login1.html',form=myForm)
總結(jié)
以上是生活随笔為你收集整理的Python Flask-表单提交方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AJAX-prototype.js实现A
- 下一篇: AJAX-jQuery实现Ajax