python - flask send_grid 异步邮件

标签 python asynchronous flask sendgrid

我已经使用 Flask 改编了 Miquel Grindberg 的书(强烈推荐)中的异步电子邮件示例,以使用 flask_sendgrid。但是,此代码导致线程中发生异常。应用程序第一次运行时运行良好,但第二次运行时出现故障。

格林伯格示例:

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])
    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

我使用 flask_sendgrid 进行翻译。

def send_async_email(app, **kwargs):
    with app.app_context():
        sendgrid.send_email(**kwargs)


def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    html = __flask.render_template(template + '.html', **kwargs)

    msg = {'html': html,'subject': subject, 'to_email': to}

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

Grindberg 的示例适用于我的谷歌帐户。但是,我想使用 Sendgrid 来卸载我的应用程序的电子邮件。我需要自己创建异步还是由 sendgrid api 处理?如果不是,我的代码有什么问题?

最佳答案

收件人handle requests concurrently你可以运行 Flask:

app.run(threaded=True)

默认情况下,Flask 使用一个线程运行,因此后续请求将被阻塞,直到有一个线程可用。在生产中,您还需要像 Gunicorn 这样的 WSGI 容器来 manage workers and threads .

关于python - flask send_grid 异步邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251679/

相关文章:

python - DJANGO-GRAPHQL-JWT:我们如何知道刷新 token 发布后有多少年了?

python - Flask Python - 从谷歌数据存储中提取信息并显示在自己的网址上

python - 在范围内调用 asyncio Future

javascript - 通过对 Flask 的函数调用更新值

javascript - 在 Flask 上运行时未添加外部 JavaScript 文件

python - WTForms 中的选择验证不会在数据库更新时更新

python - 将稀疏数据输入到 Tensorflow Estimator 中进行拟合

python - 如何在日期中添加工作日(不包括节假日)

events - 如何在 Glassfish 3.1 中结合 @Asynchronous 和 Weld/CDI 事件和 @Observes(during=TransactionPhase.AFTER_COMPLETION)

c# - 使用异步等待时出现意外结果