【发布时间】: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