gpt4 book ai didi

python - flask send_grid 异步邮件

转载 作者:行者123 更新时间:2023-11-28 17:17:53 24 4
gpt4 key购买 nike

我已经使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com