【问题标题】:flask send_grid asynchronous emailflask send_grid 异步电子邮件
【发布时间】:2017-09-01 06:39:31
【问题描述】:

我已经使用 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 的示例适用于我的 Google 帐户。但是,我想使用 Sendgrid 来卸载我的应用程序的电子邮件。我需要自己创建异步还是由 sendgrid api 处理?如果不是,我的代码有什么问题?

【问题讨论】:

    标签: python asynchronous flask sendgrid


    【解决方案1】:

    handle requests concurrently,您可以使用以下方式运行 Flask:

    app.run(threaded=True)
    

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

    【讨论】:

      猜你喜欢
      • 2017-03-12
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 2021-08-25
      • 2017-07-13
      • 2011-03-25
      相关资源
      最近更新 更多