Flask问题:正确传递app_context时遇到困难
问题解决:Flask多线程发送邮件时的app参数传递错误
错误原因
你现在的问题出在传递给Thread的参数类型错误:
current_app.app_context()返回的是一个上下文对象,而send_async_email函数期望接收的是Flask的app实例- 同时
current_app是Flask的代理对象,子线程无法直接使用,必须获取其背后实际的app实例
修正方案
只需要两步修改:
- 在
send_email函数中,获取实际的Flask app实例,而不是直接用current_app或它的上下文 - 将这个实际的app实例传给子线程的
send_async_email函数
修改后的完整代码
from threading import Thread from flask import current_app, render_template from flask_mail import Message from . import mail def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(to, subject, template, **kwargs): msg = Message(current_app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject, sender=current_app.config['FLASKY_MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) # 获取实际的app实例,而不是代理对象或上下文 app = current_app._get_current_object() # 传递实际的app实例给子线程函数 thr = Thread(target=send_async_email, args=[app, msg]) thr.start() return thr
补充说明
current_app._get_current_object()会返回当前线程中实际的Flask app实例,这个实例可以安全地传递给子线程使用send_async_email里的with app.app_context()是正确的,它会在子线程中创建Flask的上下文环境,让mail扩展能正常工作
内容的提问来源于stack exchange,提问作者J Griffin
相关产品推荐
相关产品推荐

