import wtforms from wtforms.validators import Email, Length from models import UserModel classRegisterForm(wtforms.Form): email = wtforms.StringField(validators=[Email(message='strange, something seems going wrong')]) name = wtforms.StringField(validators=[Length(min=1,max=20,message='strange, something seems going wrong')]) password = wtforms.StringField(validators=[Length(min=4,max=20,message='strange, something seems going wrong')]) defvalidate_emial(self, field): email = field.data user = UserModel.query.filter_by(email=email).first() if user: raise wtforms.ValidationError(message='strange, something seems going wrong')
使用验证类
1 2 3 4 5 6 7 8 9 10 11
from .forms import RegisterForm @index.route("/register", methods=["POST", "GET"]) defregister(): if request.method == 'POST': form = RegisterForm(request.form) if form.validate(): ... return ... else: print(form.errors) return ...
werkzeug
WSGL
WSGLWeb Server Gateway Interface
WSGL是Python Web应用程序和Web服务器之间的标准接口
Werkzeug是python提供的WSGL库
使用werkzeug.security进行数据加密
generate_password_hash 加密
check_password_hash 比较加密数据和未加密数据是否包含相同信息
加密
1 2 3 4 5 6 7 8 9
from werkzeug.security import generate_password_hash, check_password_hash defregister(): .... password = generate_password_hash(form.password.data) user = UserMode( name=form.name.data, email=form.email.data, password=password )
比较
1 2 3 4 5 6 7
@index.route("/login", methods=["POST", "GET"]) deflogin(): ... user = UserModel.query.filter_by(email=form['email']).first() if user and check_password_hash(user.password, form["password"]): session["user_id"] = user.id return ...
钩子函数
Flask中的钩子函数使用装饰器的形式定义
一些常用的钩子函数
before_request 请求之前、视图函数执行之前
after_request 请求之后、响应发送给用户之前调用
teardown_request 请求之后、响应发送给用户之后调用
before_first_request 应用启动时/处理第一个请求之前调用
after_request 应用关闭时/处理最后一个请求之后调用
before_request使用
1 2 3 4 5 6 7 8 9
# 请求之前全局存入用户信息 @app.before_request defbefore_request(): user_id = session.get('user_id') if user_id: user = UserModel.query.filter_by(id=user_id).first() setattr(g, 'user', user) else: setattr(g, 'user', None)