8-----BBS論壇

BBS論壇(八)html

8.1.發送郵箱驗證碼功能

(1)cms/resetemail.htmlgit

{%  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.jsgithub

/**
 * 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.pyajax

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

 輸入郵箱,點「獲取驗證碼」flask

 

8.2.修改郵箱功能完成

(1)utils/zlcache.py緩存

把驗證碼保存到memcached中restful

# 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.pysession

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.pyapp

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.jsdom

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

如今就能夠修改郵箱了。

相關文章
相關標籤/搜索