本文實例講述了使用Flask實現表單開發。分享給大家供大家參考,具體如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div align="center"> <h2>User Management</h2> <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>
使用html實現的表單:
用flask實現相同功能的表單:
# -*- coding:utf-8 -*- from flask import Flask, request, render_template, redirect from wtforms import Form, TextField, PasswordField, validators app = Flask(__name__) class LoginForm(Form): # validators指定一個由驗證函數組成的列表 # 在接受用戶提交的數據之前驗證數據 # 驗證函數Required()確保提交的字段不為空 username = TextField("username", [validators.Required()]) password = PasswordField("password", [validators.Required()]) # 定義user路由 @app.route("/user", methods=['GET', 'POST']) def login(): myForm = LoginForm(request.form) if request.method == 'POST': # username = request.form['username']使用request獲取數據 # password = request.form['password'] # 也可以使用類實例里的表單方法來獲取相應的數據 # validate來驗證輸入的表單數據是否有效 if myForm.username.data == "loli" and myForm.password.data == "520" and myForm.validate(): return redirect("http://www.baidu.com") else: message = "Login Failed" return render_template("form1.html", message=message, form=myForm) return render_template("form1.html", form=myForm) if __name__ == '__main__': app.run()
form1模板:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div align="center"> <h2>User Management</h2> <form method="post"> {% if message %} {{ message }} {% endif %} <br> {{ form.username }} <br> {{ form.password }} <br> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form> </div> </body> </html>
一樣的效果圖。
在WTForm3.0中Textfield被移除,使用Stringfield代替。
WTForm主要在flask中用于驗證表單。
參考官方文檔:http://dormousehole.readthedocs.io/en/latest/patterns/wtforms.html
希望本文所述對大家基于flask框架的Python程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。