注册表单
from app.modles import User class registerForm(FlaskForm): nicheng = StringField('昵称',validators=[DataRequired(message='填写昵称'),Length(3,20,message='长度不小于3 大于20')]) email = StringField('邮箱',validators=[DataRequired('填写邮箱'),Email(message='邮箱格式不正确')]) password = StringField('密码',validators=[DataRequired(message='填写密码'),Length(5,20,message='不能小于3大于20')]) password2 = StringField('重复密码', validators=[DataRequired(message='填写密码'), Length(5, 20)]) submit = SubmitField('提交') def validate_nicheng(self,field): # 请求数据库模型User 看是否存在昵称,存在则跳出异常 user = User.query.filter_by(nicheng=field.data).first() if user: raise ValidationError('昵称已存在!') def validate_email(self,field): user = User.query.filter_by(email=field.data).first() if user: raise ValidationError('邮箱已存在!')
先是默认的发送邮件
# 发送邮件 def send_email(recipients,html=None,body=None): # 使用代理app flask自带的current_app 得到当前环境下的app app = current_app._get_current_object() mes = Message(recipients=[recipients],subject='账号注册激活邮件',sender=app.config['MAIL_USERNAME']) mes.body =body mes.html = html t = Thread(target=mail_send,args=[app,mes]) t.start() def mail_send(app,mes): with app.app_context(): mail.send(mes)
对邮件url进行加密
# 注册用户,表单验证之后经过用户提交 给一个页面发送信息让其激活邮件 @user.route('/register/',methods=['GET','POST']) def register(): form = registerForm() # 重复验证密码 经过表单验证,所以不需要 if form .validate_on_submit(): # 默认是不将注册用户还未激活的信息保存到数据库中,这里是将用户注册信息做成一个字典使用一个加密算法混淆,防止爆破 token = get_token(form.nicheng.data,form.email.data,form.password.data) # 渲染的html页面 html = render_template('email_send.html',token=token) # 发送邮件 将注册人的邮件传入发送邮件的函数中 send_email(recipients=form.email.data,html=html) return render_template('ing.html',name=form.nicheng.data,email=form.email.data) return render_template('register.html',form=form) # 接收邮件激活 @user.route('/confirm/') def confirm(): token = request.args.get('token') ''' 这里有个坑点,在使用itsdangerous加密函数是会将增加 b' 和 最好一个字符 ' 在进行解密时发生错误 ''' check_token(token[2:-1]) # 注意切片 return render_template('email_register.html')
from itsdangerous import TimedJSONWebSignatureSerializer 是加密的函数
# 加密邮件注册的url 生成token def get_token(nicheng,email,password): s = serializer(current_app.config['SECRET_KEY'], expires_in=7200) token = s.dumps({"nicheng":nicheng, "email":email, "password":password}) return token # 解密邮件链接的url 将token解密成为昵称密码邮箱 def check_token(token): s = serializer(current_app.config['SECRET_KEY']) data = s.loads(token) nicheng = data.get('nicheng') email = data.get('email') password = data.get('password') user = User() user.nicheng = nicheng user.email = email user.password = password db.session.add(user) db.session.commit() return data # nicheng":nicheng,"email":email,"password":password