WTForms是一個支持多個web框架的form組件,主要用於對用戶請求數據進行驗證。html
安裝:html5
pip3 install wtforms
用戶登陸簡例:web
from flask import Flask,render_template,request,redirect from wtforms.fields import core from wtforms.fields import html5 from wtforms.fields import simple from wtforms import Form from wtforms import validators from wtforms import widgets app = Flask(__name__,template_folder="templates") class Myvalidators(object): '''自定義驗證規則''' def __init__(self,message): self.message = message def __call__(self, form, field): print(field.data,"用戶輸入的信息") if field.data == "haiyan": return None raise validators.ValidationError(self.message) class LoginForm(Form): '''Form''' name = simple.StringField( label="用戶名", widget=widgets.TextInput(), validators=[ Myvalidators(message="用戶名必須是haiyan"),#也能夠自定義正則 validators.DataRequired(message="用戶名不能爲空"), validators.Length(max=8,min=3,message="用戶名長度必須大於%(max)d且小於%(min)d") ], render_kw={"class":"form-control"} #設置屬性 ) pwd = simple.PasswordField( label="密碼", validators=[ validators.DataRequired(message="密碼不能爲空"), validators.Length(max=8,min=3,message="密碼長度必須大於%(max)d且小於%(min)d"), validators.Regexp(regex="\d+",message="密碼必須是數字"), ], widget=widgets.PasswordInput(), render_kw={"class":"form-control"} ) @app.route('/login',methods=["GET","POST"]) def login(): if request.method =="GET": form = LoginForm() # 傳遞form return render_template("login.html",form=form) else: form = LoginForm(formdata=request.form) if form.validate(): # 校驗 print("用戶提交的數據用過格式驗證,值爲:%s"%form.data) return "登陸成功" else: print(form.errors,"錯誤信息") return render_template("login.html",form=form) if __name__ == '__main__': # app.__call__() app.run(debug=True)
login.htmlflask
<body> <form action="" method="post" novalidate> <p>{{ form.name.label }} {{ form.name }} {{ form.name.errors.0 }}</p> <p>{{ form.pwd.label }} {{ form.pwd }} {{ form.pwd.errors.0 }}</p> <input type="submit" value="提交"> <!--用戶名:<input type="text">--> <!--密碼:<input type="password">--> <!--<input type="submit" value="提交">--> </form> </body>