问题来源
最近遇到FASK自定义命令中执行数据库查询特别慢的问题,有希望通过多线程并行充分利用数据库资源,加快任务安成。 刚开始时将current_app做为参数传递到线程方法,总会遇到错误"Outsiding application context"的问题。
解决方法
由于current_app返回的是一个动态映射到app的代理对象,直接传递current_app不起作用。这里需要使用current_app._get_current_object()获取代理对象中的 真实应用实例,作为参数传递给线程方法。
下面是独立线程中发送邮件的例子
from flask import current_app
def send_async_email(app, msg):
with 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._get_current_object(), msg)).start()
参考
The Flask Mega-Tutorial Part XV: A Better Application Structure
Comments