简体   繁体   English

烧瓶对象没有属性app_context

[英]Flask object has no attribute app_context

I'm trying to send emails periodically with flask mail, but I'm stuck with this error: Flask object has no attribute app_context 我正在尝试定期发送带有Flask邮件的电子邮件,但是我遇到了以下错误:Flask对象没有属性app_context

def mail_periodic():
    print "sending mail at " +time.ctime()

    app = current_app._get_current_object()

    msg = Message("no-reply: Avantgarde.Rentals",
                  sender="avantgarde.rentals.noreply@gmail.com",
                  )

    msg.add_recipient('aladinne.k@gmail.com')

    msg.body = 'Email periodic '
    mail2 = Mail(app)
    with app.app_context():
        mail2.send(msg)
    print"email sent "

threading.Timer(5, mail_periodic).start()



@app.route('/startcronemailing')
def startcronemailing():
    try:
        mail_periodic()
    except Exception, exception:
            return exception.message
    return "crone mailing started"

the exception that i got : 我得到的例外:

Exception in thread Thread-3:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python27\lib\threading.py", line 1073, in run
    self.function(*self.args, **self.kwargs)
  File "app.py", line 113, in mail_periodic
    host_link='http://' + request.host,
  File "C:\Python27\lib\site-packages\werkzeug\local.py", line 336, in __getattr__
    return getattr(self._get_current_object(), name)
  File "C:\Python27\lib\site-packages\werkzeug\local.py", line 295, in _get_current_object
    return self.__local()
  File "C:\Python27\lib\site-packages\flask\globals.py", line 19, in _lookup_object
    raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context

please note that even if i use another mailing service like sendgrid i got the same error 请注意,即使我使用了sendgrid之类的其他邮件服务,我也会遇到相同的错误

You have to pass app instance as args. 您必须将应用程序实例作为args传递。 If you use current_app._get_current_object() to get app instance inside target function, you will not get the right app in another thread. 如果使用current_app._get_current_object()在目标函数中获取应用程序实例,则不会在另一个线程中获取正确的应用程序。 For example: 例如:

from threading import Thread

from flask import current_app
from flask_mail import Message

from bluelog.extensions import mail

def _send_async_mail(app, message):  # target function
    with app.app_context():
        mail.send(message)

def send_async_mail(subject, to, html):
    app = current_app._get_current_object()  # get the real app instance
    message = Message(subject, recipients=[to], html=html)
    thr = Thread(target=_send_async_mail, args=[app, message])  # pass app
    thr.start()
    return thr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM