1. 程式人生 > >Flask-mail 發郵件慢(即使異步)

Flask-mail 發郵件慢(即使異步)

app sta 每一個 current ssa () rec class .com

Flask-mail 發郵件慢(即使異步)

一開始,按照狗書上的代碼異步發郵件,但是發現原本響應只需要150ms的頁面加了郵件發送就變成了5s響應(這怕不是假異步)

狗書的異步發郵件代碼:

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)


def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(app.config[‘FLASKY_MAIL_SUBJECT_PREFIX‘] + subject,
               sender=app.config[‘FLASKY_MAIL_SENDER‘], recipients=[to])
    print datetime.datetime.now().second
    msg.body = render_template(template + ‘.txt‘, **kwargs)
    msg.html = render_template(template + ‘.html‘, **kwargs)
    print datetime.datetime.now().second
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    print datetime.datetime.now().second
    return thr

之後我在每一個可能延時的位置加了一句print datetime.datetime.now().second,最後發現,真正拖時間的地方居然是在Message初始化的時候!

msg = Message(app.config[‘FLASKY_MAIL_SUBJECT_PREFIX‘] + subject,
               sender=app.config[‘FLASKY_MAIL_SENDER‘], recipients=[to])

於是自己優化了一下發郵件的代碼,把Message初始化的部分也放進了異步線程中。

優化後,速度明顯提升:)

我的優化代碼:

def send_async_email(app, to, subject, template_done_html, template_done_txt):
    with app.app_context():
        msg = Message(app.config[‘FLASKY_MAIL_SUBJECT_PREFIX‘] + subject,
                      sender=app.config[‘FLASKY_MAIL_SENDER‘], recipients=[to])
        msg.body = template_done_txt
        msg.html = template_done_html
        mail.send(msg)


def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    template_done_html = render_template(template + ‘.html‘, **kwargs)
    template_done_txt = render_template(template + ‘.txt‘, **kwargs)
    thr = Thread(target=send_async_email, args=[app, to, subject, template_done_html, template_done_txt])
    thr.start()
    return thr

Flask-mail 發郵件慢(即使異步)