# 安装
pip install flask-wtf
# # 手写判断逻辑
from flask import Flask,request,render_template
app = Flask(__name__)
@.route("/")
def index():
return "首页"
@app.route("/regist",methods = ['GET','POST'])
def regist():
if requst.method == 'GET':
return render_template('regist.html')
else:
username = request.form.get("username")
password = request.form.get("password")
password_repate = request.form.get("password_repate")
# 其他判断逻辑,如长度,密码是否一致等
if __name__ == '__main__':
app.run(debug =True)
**# flask-wtf 验证**
from wtforms import Form,StringField,validators
from wtforms.validators import length,Regexp,EqualTo
# validators 验证器
# EqualTo 验证是否一致
class RegistForm(Form):
username = StringField(validators[Length(min=3,max = 10)])
password = StringField(validators[Length(min=3,max = 10)])
password_repate = StringField(validators[Length(min=3,max = 10),EqualTo("passwrod")])
@app.route("/regist",methods = ['GET','POST'])
def regist():
if requst.method == 'GET':
return render_template('regist.html')
else:
form = RegistForm(request.form)
if form.validate():
return "successfull"
else:
print("")
return "fail"
常用表单验证
# 邮箱验证
email = StringField(validators=[Email()])
# 年龄验证
age = IntegerField(validators=[NumberRange(1,120,message='年龄信息有误')])
# 必填项验证
username = StringField(validators=[InputRequired(message='用户名必须要填写')])
# 手机号验证
phone = StringField(validators=[Regexp(r'1[38]\d{9}')])
# url 验证
info = StringField(validators=[URL()])
# 验证码 validata_captcha 名称固定
captcha = StringField(validators[Length(min=4,max = 4)])
def validata_captcha(self,field):
print(type(field))
if field.data != '4587':
raise ValidationError('验证码错误')
文件上传
<form action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>头像</td>
<td><input type="file" name="image_file"></td>
</tr>
<tr>
<td>描述</td>
<td><input type="text" name="desc"></td>
</tr>
<tr>
<td><input type=""submit value="上传"></td>
</tr>
</table>
</form>
# 接收上传 上来的数据
desc = request.form.get('desc')
image_file = request.files.get('image_file')
# image_file.filename 文件的名字
image_file.save(os.path.join('images',image_file.filename))