Flask-mail 发邮件慢(即使异步)

本文详细探讨了使用Flask-Mail发送邮件导致响应时间显著增加的问题,并分享了一种有效的优化方案,通过将Message对象的初始化过程放入异步线程中,显著提升了邮件发送速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/santiego/p/10356001.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值