flask框架中使用wtforms
阿新 • • 發佈:2019-01-15
用戶輸入 post 框架 tex call route obj validator html5
一、什麽是wtforms
WTForms是一個支持多個web框架的form組件,主要用於對用戶請求數據進行驗證。
安裝:
pip3 install WTForms
二、簡單使用wtforms組件
(一)用戶登陸驗證
py文件代碼:
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 importForm 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() 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.run(debug=True)
login.html:
<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>
前端頁面效果:
(二)用戶註冊驗證
py文件代碼:
from flask import Flask,render_template,redirect,request from wtforms import Form from wtforms.fields import core from wtforms.fields import html5 from wtforms.fields import simple from wtforms import validators from wtforms import widgets app = Flask(__name__,template_folder="templates") app.debug = True =======================simple=========================== class RegisterForm(Form): name = simple.StringField( label="用戶名", validators=[ validators.DataRequired() ], widget=widgets.TextInput(), render_kw={"class":"form-control"}, default="haiyan" ) pwd = simple.PasswordField( label="密碼", validators=[ validators.DataRequired(message="密碼不能為空") ] ) pwd_confim = simple.PasswordField( label="重復密碼", validators=[ validators.DataRequired(message=‘重復密碼不能為空.‘), validators.EqualTo(‘pwd‘,message="兩次密碼不一致") ], widget=widgets.PasswordInput(), render_kw={‘class‘: ‘form-control‘} ) ========================html5============================ email = html5.EmailField( #註意這裏用的是html5.EmailField label=‘郵箱‘, validators=[ validators.DataRequired(message=‘郵箱不能為空.‘), validators.Email(message=‘郵箱格式錯誤‘) ], widget=widgets.TextInput(input_type=‘email‘), render_kw={‘class‘: ‘form-control‘} ) ===================以下是用core來調用的======================= gender = core.RadioField( label="性別", choices=( (1,"男"), (1,"女"), ), coerce=int #限制是int類型的 ) city = core.SelectField( label="城市", choices=( ("bj","北京"), ("sh","上海"), ) ) hobby = core.SelectMultipleField( label=‘愛好‘, choices=( (1, ‘籃球‘), (2, ‘足球‘), ), coerce=int ) favor = core.SelectMultipleField( label="喜好", choices=( (1, ‘籃球‘), (2, ‘足球‘), ), widget = widgets.ListWidget(prefix_label=False), option_widget = widgets.CheckboxInput(), coerce = int, default = [1, 2] ) def __init__(self,*args,**kwargs): #這裏的self是一個RegisterForm對象 ‘‘‘重寫__init__方法‘‘‘ super(RegisterForm,self).__init__(*args, **kwargs) #繼承父類的init方法 self.favor.choices =((1, ‘籃球‘), (2, ‘足球‘), (3, ‘羽毛球‘)) #吧RegisterForm這個類裏面的favor重新賦值 def validate_pwd_confim(self,field,): ‘‘‘ 自定義pwd_config字段規則,例:與pwd字段是否一致 :param field: :return: ‘‘‘ # 最開始初始化時,self.data中已經有所有的值 if field.data != self.data[‘pwd‘]: # raise validators.ValidationError("密碼不一致") # 繼續後續驗證 raise validators.StopValidation("密碼不一致") # 不再繼續後續驗證 @app.route(‘/register‘,methods=["GET","POST"]) def register(): if request.method=="GET": form = RegisterForm(data={‘gender‘: 1}) #默認是1, return render_template("register.html",form=form) else: form = RegisterForm(formdata=request.form) if form.validate(): #判斷是否驗證成功 print(‘用戶提交數據通過格式驗證,提交的值為:‘, form.data) #所有的正確信息 else: print(form.errors) #所有的錯誤信息 return render_template(‘register.html‘, form=form) if __name__ == ‘__main__‘: app.run()
register.html:
<body> <h1>用戶註冊</h1> <form method="post" novalidate style="padding:0 50px"> {% for item in form %} <p>{{item.label}}: {{item}} {{item.errors[0] }}</p> {% endfor %} <input type="submit" value="提交"> </form> </body>
前端頁面效果:
flask框架中使用wtforms