zoukankan      html  css  js  c++  java
  • 【简说Python WEB】flask-mail电子邮件异步Asynchronous

    系统环境:Ubuntu 18.04.1 LTS

    Python使用的是虚拟环境:virutalenv

    Python的版本:Python 3.6.9

    flask-mail电子邮件异步Asynchronous

    通过把发送电子邮件放到后台进程中。修改如下:

    from threading import Thread
    
    def send_async_email(app, msg):
        with app.app_context():
            mail.send(msg)
            
    def send_email(to, subject, template, **kwargs):
        msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
                      sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
        msg.body = render_template(template + '.txt', **kwargs)
        msg.html = render_template(template + '.html', **kwargs)
        thr = Thread(target=send_async_email, args=[app, msg])
        thr.start()
        return thr
    

    上述代码,通过app.app_context()人工创建应用上下文场景。在这个场景之下,app会异步发送邮件。

    如何实现呢?、

    通过调用:

    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr
    

    启动一个线程,让线程在后台处理邮件发送的任务。

    但是如果有大量的邮件发送,那么就需要任务队列Celery了。

  • 相关阅读:
    基于Metaweblog API 接口一键发布到国内外主流博客平台
    uva144 Student Grants
    Uva 10452
    Uva 439 Knight Moves
    Uva 352 The Seasonal War
    switch语句
    java——基础知识
    我的lua学习2
    codeforces 431 D. Random Task 组合数学
    codeforces 285 D. Permutation Sum 状压 dfs打表
  • 原文地址:https://www.cnblogs.com/zhangshengdong/p/12558988.html
Copyright © 2011-2022 走看看