[Jane said Python WEB] flask-mail e-mail Asynchronous asynchronous

System environment:Ubuntu 18.04.1 LTS

Python uses a virtual environment:virutalenv

Python version:Python 3.6.9

flask-mail e-mail Asynchronous asynchronous

By sending e-mail in the background process. amend as below:

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

The code, by app.app_context()manually created application context scenario. Under this scenario, app asynchronously send messages.

How to achieve it? ,

By calling:

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

Start a thread, the thread processing tasks so that messages sent in the background.

But if there is a lot of mail, you will need to mission queue Celeryup.

Guess you like

Origin www.cnblogs.com/zhangshengdong/p/12558988.html
Recommended