flask(五)优化登录-对表单进行过滤验证
admin/forms.py文件添加代码:
from wtforms import Form, StringField
from wtforms.validators import InputRequired, Length
class LoginForm(Form):
username = StringField(
label='用户名',
validators=[
InputRequired('用户名为必填项'),
Length(4,20,'用户名长度为4到20')
]
)
password = StringField(
label='密码',
validators=[
InputRequired('密码为必填项'),
Length(6,9,'密码长度为6到9')
]
)
修改admin/views.py中login方法:
def login():
error = None
if request.method == 'GET':
return render_template('admin/login.html')
else:
form=LoginForm(request.form)
if form.validate():
user = request.form.get('username')
pwd = request.form.get('password')
users = Users.query.filter_by(username=user).first()
if users:
if user == users.username and users.chek_password(pwd):
session['user_id'] = users.uid # 用户id存于session
return redirect(url_for('admin.index'))
else:
error = "用户名或密码错误"
return render_template('admin/login.html',message=error)
else:
return render_template('admin/login.html',message="别试了,没有此用户!")
return render_template('admin/login.html', message=form.errors)