WTForms 是用于web开发的灵活的表单验证和呈现库,它可以与您选择的任何web框架和模板引擎一起工作,并支持数据验证、CSRF保护、国际化等,运用WTForms框架并配合Flask可实现一个带有基本表单验证功能的用户注册与登录页面,经过美化的页面可以直接应用到项目中。
- WTForms 需要额外安装PIP包
- pip install WTForms email_validator
实现用户注册页面
在templates
目录下新建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel='stylesheet' href="https://cdn.lyshark.com/javascript/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://cdn.lyshark.com/javascript/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://cdn.lyshark.com/javascript/other/my_login.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<form action="/register" method="post" class="form-horizontal">
<span class="heading">用 户 注 册</span>
<div class="form-group">
{{ form.username }}
<i class="fa fa-user"></i>
<a href="/login" class="fa fa-question-circle"></a>
</div>
<div class="form-group">
{{ form.email }}
<i class="fa fa-envelope"></i>
</div>
<div class="form-group">
{{ form.password }}
<i class="fa fa-lock"></i>
</div>
<div class="form-group">
{{ form.RepeatPassword }}
<i class="fa fa-unlock-alt"></i>
</div>
{{ form.submit }}
</form>
</div>
</div>
</div>
</body>
</html>
Flask 后端部分使用如下代码:
from flask import Flask, render_template, request, redirect
from wtforms import Form,validators,widgets
from wtforms.fields import simple
app = Flask(import_name=__name__,
static_url_path='/python', # 配置静态文件的访问url前缀
static_folder='static', # 配置静态文件的文件夹
template_folder='templates') # 配置模板文件的文件夹
class RegisterForm(Form):
username = simple.StringField(
#label='注册用户:',
validators=[
validators.DataRequired(message='用户名不能为空'),
validators.Length(min=6, max=18, message='用户名长度必须大于%(min)d且小于%(max)d')
],
widget=widgets.TextInput(),
render_kw={'class': 'form-control',
"placeholder":"输入注册用户名"}
)
email = simple.StringField(
#label='用户邮箱:',
validators=[validators.DataRequired(message='邮箱不能为空'),validators.Email(message="邮箱格式输入有误")],
render_kw={'class':'form-control',
"placeholder":"输入Email邮箱"}
)
password = simple.PasswordField(
#label='用户密码:',
validators=[
validators.DataRequired(message='密码不能为空'),
validators.Length(min=5, message='用户名长度必须大于%(min)d'),
validators.Regexp(regex="[0-9a-zA-Z]{5,}",message='密码不允许使用特殊字符')
],
widget=widgets.PasswordInput(),
render_kw={'class': 'form-control',
"placeholder":"输入用户密码"}
)
RepeatPassword = simple.PasswordField(
#label='重复密码:',
validators=[
validators.DataRequired(message='密码不能为空'),
validators.Length(min=5, message='密码长度必须大于%(min)d'),
validators.Regexp(regex="[0-9a-zA-Z]{5,}",message='密码不允许使用特殊字符'),
validators.EqualTo("password",message="两次密码输入必须一致,龟孙")
],
widget=widgets.PasswordInput(),
render_kw={'class': 'form-control',
"placeholder":"再次输入密码"}
)
submit = simple.SubmitField(
label="用 户 注 册",
render_kw={ "class":"btn btn-success" }
)
@app.route('/register', methods=['GET', 'POST'])
def Register():
if request.method == 'GET':
RetForm = RegisterForm()
return render_template('index.html', form=RetForm)
else:
RetForm = RegisterForm(formdata=request.form)
if RetForm.validate():
print('接收到数据:', RetForm.data)
return '''<script>alert('您的注册请求已提交!');</script>'''
else:
print(RetForm.errors)
return render_template('index.html', form=RetForm)
if __name__ == '__main__':
app.run(host="127.0.0.1", port=80, debug=False)
代码运行效果如下:
实现用户登录页面
在templates
目录下新建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel='stylesheet' href="https://cdn.lyshark.com/javascript/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://cdn.lyshark.com/javascript/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://cdn.lyshark.com/javascript/other/my_login.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<form action="/login" method="post" class="form-horizontal">
<span class="heading">用 户 登 录</span>
<div class="form-group">
{{ form.username }}
<i class="fa fa-user"></i>
</div>
<div class="form-group help">
{{ form.password }}
<i class="fa fa-lock"></i>
<a href="#" class="fa fa-question-circle"></a>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">登 录 后 台</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Flask 后端部分使用如下代码:
from flask import Flask, render_template, request, redirect
from wtforms import Form,validators,widgets
from wtforms.fields import simple,html5
app = Flask(import_name=__name__,
static_url_path='/python', # 配置静态文件的访问url前缀
static_folder='static', # 配置静态文件的文件夹
template_folder='templates') # 配置模板文件的文件夹
class LoginForm(Form):
username = simple.StringField(
validators=[
validators.DataRequired(message=''),
validators.Length(min=4, max=15, message=''),
validators.Regexp(regex="[0-9a-zA-Z]{4,15}", message='')
],
widget=widgets.TextInput(),
render_kw={"class":"form-control",
"placeholder":"请输入用户名或电子邮件"}
)
password = simple.PasswordField(
validators=[
validators.DataRequired(message=''),
validators.Length(min=5, max=15,message=''),
validators.Regexp(regex="[0-9a-zA-Z]{5,15}",message='')
],
widget=widgets.PasswordInput(),
render_kw={"class":"form-control",
"placeholder":"请输入密码"}
)
@app.route("/login",methods=['GET','POST'])
def Login():
if request.method == 'GET':
RetForm = LoginForm()
return render_template('index.html', form=RetForm)
else:
RetForm = LoginForm(formdata=request.form)
if RetForm.validate():
temp = RetForm.data
print("接收到数据:",temp)
return '''<script type="text/javascript">alert('登录完成!');</script>'''
return render_template('index.html', form=RetForm)
if __name__ == '__main__':
app.run(host="127.0.0.1", port=80, debug=False)
代码运行效果如下: