【简说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了。

猜你喜欢

转载自www.cnblogs.com/zhangshengdong/p/12558988.html