前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >BBS论坛(八)

BBS论坛(八)

作者头像
zhang_derek
发布2019-02-13 16:03:43
1.5K0
发布2019-02-13 16:03:43
举报
文章被收录于专栏:有趣的django有趣的django

8.1.发送邮箱验证码功能

(1)cms/resetemail.html

{%  from 'common/_macros.html' import static %}

{% block head %}
    <script src="{{ static('cms/js/resetemail.js')}}"></script>
{% endblock %}

 <input type="email" name="email" placeholder="新邮箱" class="form-control">
 <span class="input-group-addon" id="captcha-btn" style="cursor: pointer">获取验证码</span>

(2)cms/js/resetemail.js

/**
 * Created by derekon 2018/6/4.
 */

$(function () {
    $("#captcha-btn").click(function (event) {
        event.preventDefault();
        var email = $("input[name='email']").val();
        if(!email){
            zlalert.alertInfoToast('请输入邮箱');
        }
        zlajax.get({
           'url': '/cms/email_captcha/',
            'data': {'email':email},
            'success': function (data) {
                if(data['code'] == 200){
                    zlalert.alertSuccessToast('邮件已发送成功!请注意查收!');
                }else{
                    zlalert.alertInfo(data['message']);
                }
            },
            'fail':function (error) {
                zlalert.alertNetworkError();
            }
        });
    });
});

(3)cms/views.py

@bp.route('/email_captcha/')
def email_captcha():
    #获取要修改的邮箱
    email = request.args.get('email')
    if not email:
        return restful.params_error('请输入要修改的邮箱')
    #得到大小写字母的列表
    source = list(string.ascii_letters)
    #得到大小写字母的列表 + 0到9的数字字符串
    source.extend(map(lambda x: str(x), range(0, 10)))
    # 随机取六位作为验证码
    captcha = "".join(random.sample(source, 6))
    #给这个邮箱发送邮件验证码
    message = Message(subject='derek论坛密码修改邮件发送', recipients=[email,], body='你的验证码是:%s'%captcha)
    try:
        mail.send(message)
    except:
        return restful.server_error()
    return restful.success()

 输入邮箱,点“获取验证码”

8.2.修改邮箱功能完成

(1)utils/zlcache.py

把验证码保存到memcached中

# utils/zlcache.py

import memcache

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

def set(key,value,timeout=60):     #过期时间60s
    return cache.set(key,value,timeout)

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

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

(2)cms/views.py

zlcache.set(email,captcha) 把邮箱和验证码相关联保存到memcached中
@bp.route('/email_captcha/')
def email_captcha():
   .
   .
   .
   . 
    try:
        mail.send(message)
    except:
        return restful.server_error()
    #把邮箱和验证码保存到memcached中
    zlcache.set(email,captcha)
    return restful.success()

(3)cms/forms.py

from utils import zlcache
from wtforms import ValidationError
from flask import g

class ResetEmailForm(BaseForm):
    email = StringField(validators=[Email(message="请输入正确格式的邮箱")])
    captcha = StringField(validators=[Length(min=6,max=6,message='请输入正确的邮箱验证码')])
    # 自定义验证
    def validate_captcha(self,field):
        #form要提交的验证码和邮箱
        captcha = field.data
        email = self.email.data
        #缓存里面保存的邮箱对应的验证码
        captcha_cache = zlcache.get(email)
        #如果缓存中没有这个验证码,或者缓存中的验证码跟form提交的验证码不相等(不区分大小写)
        # 两个有一个不成立,就抛异常
        if not captcha_cache or captcha.lower() != captcha_cache.lower():
            raise ValidationError('邮箱验证码错误!')

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

(4)cms/js/resetemail.js

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

        var email = emailE.val();
        var captcha = captcheE.val();

        zlajax.post({
            'url': '/cms/resetemail/',
            'data': {'email': email, 'captcha': captcha},
            'success': function (data) {
                if (data['code'] == 200) {
                    emailE.val("");
                    captcheE.val("");
                    zlalert.alertSuccessToast('恭喜!邮箱修改成功');
                } else {
                    zlalert.alertInfo(data['message']);
                }
            },
            'fail': function (error) {
                zlalert.alertNetworkError();
            }
        });
    });
});

(5)cms/views.py

class ResetEmail(views.MethodView):
    def get(self):
        return render_template('cms/cms_resetemail.html')

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

现在就可以修改邮箱了。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-06-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 8.1.发送邮箱验证码功能
  • 8.2.修改邮箱功能完成
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档