• 8-----BBS论坛


    BBS论坛(八)

    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())

    现在就可以修改邮箱了。

  • 相关阅读:
    数据库的三级封锁协议
    TCP的三次握手与四次释放
    数据库事务四大特性
    从购买服务器到建站,从0打造自己的网络领地。
    经典网络还是VPC,开发者作何选择?
    【黑客解析】黑客是如何实现数据库勒索的?
    基于OGG的Oracle与Hadoop集群准实时同步介绍
    hadoop伪分布式搭建
    在云服务器上体验Docker
    Nginx简单入门教学,包学包会,让你不再依赖伪大神!
  • 原文地址:https://www.cnblogs.com/edeny/p/10020903.html
Copyright © 2020-2023  润新知