Flask对象没有属性app\u contex

2024-10-01 13:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用flask mail定期发送电子邮件,但我遇到了一个错误:flask对象没有属性app\u 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"

我得到的例外是:

^{pr2}$

请注意,即使我使用另一个邮件服务,如sendgrid,我也会遇到同样的错误


Tags: comappflaskdef错误contextexceptionmail
1条回答
网友
1楼 · 发布于 2024-10-01 13:34:17

必须将应用程序实例作为参数传递。如果使用current_app._get_current_object()在目标函数内获取应用实例,则无法在其他线程中获得正确的应用程序。例如:

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

相关问题 更多 >