将Flask应用程序实例设置为配置
我正在使用应用程序工厂的蓝图,因此无法导入应用程序实例。你们看到将将Flask应用程序实例设置为配置,flask,Flask,我正在使用应用程序工厂的蓝图,因此无法导入应用程序实例。你们看到将app设置到配置中有什么问题吗 def create_app(): app = Flask(__name__) app.config['app'] = app with app.app_context(): configure_app(app) configure_blueprints(app) ... 现在可以通过current_app.config['a
app
设置到配置中有什么问题吗
def create_app():
app = Flask(__name__)
app.config['app'] = app
with app.app_context():
configure_app(app)
configure_blueprints(app)
...
现在可以通过current_app.config['app']
从不同的模块访问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()
在
Thread
参数中单独使用current\u app
,我会收到一个错误,说我在应用程序上下文之外工作。使用current_app.config['app']确实有效,我只想知道是否有其他方法,或者这样做是否有任何错误?这是因为current_app
只是线程本地应用的代理。这应该解决这个问题:
app=current\u app.\u获取当前对象()
这会将原始应用程序对象交还给您。您的配置示例之所以有效,是因为它还使用原始应用程序而不是代理
现在,您可以将其传递到新线程上,如下所示:
Thread(target=send\u async\u email,args=(app,msg)).start()
也就是说,将应用程序设置为app.config的一项是一个坏主意,因为它是递归的