Python 异步使用Flask Mail会导致;运行时错误:在应用程序上下文之外工作;

Python 异步使用Flask Mail会导致;运行时错误:在应用程序上下文之外工作;,python,flask,python-multithreading,flask-mail,Python,Flask,Python Multithreading,Flask Mail,我正在尝试异步发送一些邮件(基于中的代码)。但是,关于在应用程序上下文之外工作,我遇到了以下错误。如何解决此问题 Traceback (most recent call last): File "C:\Users\Primoz\Desktop\RecycleFlaskServer\recycleserver\helpers.py", line 17, in send_async_email mail.send(msg) File "C:\Python33\lib\site-pac

我正在尝试异步发送一些邮件(基于中的代码)。但是,关于在应用程序上下文之外工作,我遇到了以下错误。如何解决此问题

Traceback (most recent call last):
  File "C:\Users\Primoz\Desktop\RecycleFlaskServer\recycleserver\helpers.py", line 17, in send_async_email
    mail.send(msg)
  File "C:\Python33\lib\site-packages\flask_mail-0.9.0-py3.3.egg\flask_mail.py", line 434, in send
    message.send(connection)
  File "C:\Python33\lib\site-packages\flask_mail-0.9.0-py3.3.egg\flask_mail.py", line 369, in send
    connection.send(self)
  File "C:\Python33\lib\site-packages\flask_mail-0.9.0-py3.3.egg\flask_mail.py", line 173, in send
    email_dispatched.send(message, app=current_app._get_current_object())
  File "C:\Python33\lib\site-packages\werkzeug-0.9.4-py3.3.egg\werkzeug\local.py", line 297, in _get_current_object
    return self.__local()
  File "C:\Python33\lib\site-packages\flask-0.10.1-py3.3.egg\flask\globals.py", line 34, in _find_app
    raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context

代码应在应用程序上下文中运行。使用app.app\u context()添加


如果我们使用工厂模式来创建应用程序呢?这是flask文档中的评论:“当使用app factory模式或编写可重用的蓝图或扩展时,根本不会有要导入的应用程序实例。”我们可以访问当前的_app proxi变量,但只能访问视图中的函数。但问题是,如果我们使用线程,那么我们根本无法访问这个curren_应用程序代理。这意味着无法使用应用程序工厂模式发送异步电子邮件。如果使用应用程序工厂,请导入应用程序创建功能并创建一个:
app=create\u app(*args)
并将其与
with
语句一起使用
from flask import Flask
from flask.ext.mail import Mail
app = Flask(__name__)
app.config.from_object('recycleserver.settings')
mail = Mail(app)

def async(f):
    def wrapper(*args, **kwargs):
        thr = Thread(target = f, args = args, kwargs = kwargs)
        thr.start()
    return wrapper

@async
def send_async_email(msg):
    mail.send(msg)

def send_simple_mail(subject, sender, to_who, text_body="", html_body=""):
    msg = Message(subject=subject,sender=sender, recipients=to_who)
    msg.body = text_body
    msg.html = html_body
    send_async_email(msg)
 @async
 def send_async_email(msg):
    with app.app_context():
       mail.send(msg)