将Flask应用实例设置为配置

时间:2018-09-22 03:25:38

标签: flask

我在应用程序工厂中使用了蓝图,因此无法导入应用程序实例。你们在将app设置为配置时是否看到任何问题?

def create_app():
    app = Flask(__name__)
    app.config['app'] = app
    with app.app_context():
        configure_app(app)
        configure_blueprints(app)
        ...

现在app可以通过current_app.config['app']从另一个模块访问

app = current_app.config['app']
with app.app_context():
    ...

这里是一个真实的例子:

from flask import current_app

def send_async_email(current_app, msg):
    with current_app.app_context():
        mail.send(msg)


def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    Thread(target=send_async_email,
           args=(current_app.config['app'], msg)).start()

current_app参数中单独使用Thread时,我收到一条错误消息,指出我在应用程序上下文之外工作。使用current_app.config ['app']确实有效,我只想知道是否有其他方法,或者这样做有什么问题?

1 个答案:

答案 0 :(得分:0)

这是因为current_app只是线程本地应用程序的代理。这应该可以解决:

app= current_app._get_current_object()

这将使您退回原始应用程序对象。您的配置示例之所以有效,是因为它还使用了原始应用而不是代理。

现在,您可以像这样在新线程上传递它:

Thread(target=send_async_email, args=(app, msg)).start()

话虽如此,将应用程序设置为app.config的一项是一个坏主意,因为它是递归的。

相关问题