一百零六:CMS系统之修改邮箱功能完成

这里采用把验证码放到memcached中,所以封装一个memcached的操作

import memcache

cache = memcache.Client(['127.0.0.1:11211'], debug=True)


def set(key, value, timeout=60):
return cache.set(key, value, timeout)


def get(key):
return cache.get(key)


def delete(key):
return cache.delete(key)

form验证

from wtforms import StringField, IntegerField
from wtforms.validators import Email, InputRequired, Length, EqualTo, ValidationError
from flask import g

from ..forms import BaseForm
from utils import cmscache


class ResetEmailForm(BaseForm):
email = StringField(validators=[InputRequired(message='请输入邮箱'), Email(message='邮箱格式错误')])
captcha = StringField(validators=[Length(6, 6, message='验证码长度错误')])

def validate_email(self, field):
if field.data == g.cms_user.email:
raise ValidationError('要修改的邮箱为当前使用的邮箱')

def validate_captcha(self, field):
captcha = field.data
email = self.email.data
captcha_cache = cmscache.get(email)
if not captcha_cache or captcha.lower() != captcha_cache.lower():
raise ValidationError('邮箱验证码错误')

js

$(function () {
$('#submit').click(function (event) {
event.preventDefault();
var emailElement = $('input[name="email"]');
var captchaElement = $('input[name="captcha"]');

var email = emailElement.val();
var captcha = captchaElement.val();
http.post({
'url': '/cms/resetemail/',
'data': {
'email': email,
'captcha': captcha
},
'success': function (data) {
if(data['code'] == 200){
xtalert.alertSuccessToast('修改邮箱成功');
emailElement.val('');
captchaElement.val('');
}else{
xtalert.alertInfo(data['message']);
}
},
'fail': function (error) {
xtalert.alertNetworkError();
}
})
});
});

视图

class ResetEmailView(views.MethodView):
decorators = [login_required]

def get(self):
return render_template('cms/cms_resetemail.html')

def post(self):
form = ResetEmailForm(request.form)
if form.validate():
g.cms_user.email = form.email.data
db.session.commit()
return restful.success()
else:
return restful.params_error(form.get_error())

原文地址:https://www.cnblogs.com/zhongyehai/p/11924433.html