Flask-mail:如何一次处理多个电子邮件请求

Flask-mail: How to handle multiple email requests at once

所以我编写了一个专用的 flask 应用程序来为我的应用程序处理电子邮件并将其部署在 heroku 上。我在其中设置了发送电子邮件的路线:

@app.route('/send', methods=['POST'])
def send_now():
    with app.app_context():
      values = request.get_json()
      email = values['email']
      code = values['code']
      secret_2 = str(values['secret'])
      mail = Mail(app)
      msg = Message("Password Recovery",sender="no*****@gmail.com",recipients=[email])
      msg.html = "<h1>Your Recovery Code is: </h1><p>"+str(code)+"</p>"
      if secret == secret_2:
        mail.send(msg)
        response = {'message': 'EmailSent'}
        return jsonify(response), 201

它一次对单个用户工作正常,但是当多个用户发送一个 POST 请求时,客户端用户需要等到 POST returns 一个 201。因此等待时间不断增加(它甚至可能不会发送)。那么我该如何处理才能容纳多个并发用户。线程?缓冲?我不知道

您需要通过 Python 中的异步线程调用来发送邮件。查看此代码示例并在您的代码中实现。

from threading import Thread
from app import app

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()

这将允许在后台发送邮件。