zoukankan      html  css  js  c++  java
  • Flask-mail 发邮件慢(即使异步)

    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
    
  • 相关阅读:
    Ubuntu完全教程,让你成为Ubuntu高手!
    Centos7安装完毕后重启提示Initial setup of CentOS Linux 7 (core)的解决方法
    MS SQL操作Xml示例
    MY SQL sql_mode设置
    MS SQL " 无法启动分布式事务"问题的解决思路
    MS SQL常用系统表汇总
    SQL不同服务器数据库之间数据操作整理
    OPENQUERY用法
    SQL Compare 10.4.8.87 Edition 数据库比较工具 完全破解+使用教程
    各种主流 SQLServer 迁移到 MySQL 工具对比
  • 原文地址:https://www.cnblogs.com/santiego/p/10356001.html
Copyright © 2011-2022 走看看