1.问题记录
问题描述:在使用flask_apscheduler调用内置api /scheduler/jobs
添加job任务接口时,报错No application found. Either work inside a view function or push an application context.
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
执行任务异常
Traceback (most recent call last):
File "D:\anaconda3\lib\site-packages\sqlalchemy\util\_collections.py", line 1020, in __call__
return self.registry[key]
KeyError: <greenlet.greenlet object at 0x0B277D38 (otid=0x0C7A9410) current active started main>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\workspace\python_spyder\apscheduler_manage-main\app\common\flask_apscheduler.py", line 105, in handle_listener_all_job
job = ApschedulerJobInfo.query.order_by(ApschedulerJobInfo.id.desc()).filter(
File "D:\anaconda3\lib\site-packages\flask_sqlalchemy\__init__.py", line 552, in __get__
return type.query_class(mapper, session=self.sa.session())
File "D:\anaconda3\lib\site-packages\sqlalchemy\orm\scoping.py", line 78, in __call__
return self.registry()
File "D:\anaconda3\lib\site-packages\sqlalchemy\util\_collections.py", line 1022, in __call__
return self.registry.setdefault(key, self.createfunc())
File "D:\anaconda3\lib\site-packages\sqlalchemy\orm\session.py", line 3309, in __call__
return self.class_(**local_kw)
File "D:\anaconda3\lib\site-packages\flask_sqlalchemy\__init__.py", line 174, in __init__
self.app = app = db.get_app()
File "D:\anaconda3\lib\site-packages\flask_sqlalchemy\__init__.py", line 1042, in get_app
raise RuntimeError(
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
2.问题分析
return type.query_class(mapper, session=self.sa.session())
self.app =app = db.get_app()
File “D:\anaconda3\lib\site-packages\flask_sqlalchemy_init_.py”, line1042, in get_app
raise RuntimeError( RuntimeError: No application found. Either work inside a view function or push an application context. See
http://flask-sqlalchemy.pocoo.org/contexts/.
经过日志排查发现是在db session调用时抛出的错误,因此想到可能是初始化sqlalchemy后,没有将app应用对象传给db导致无法获取到上下文对象,因此接口调用时无法获取到app对象
修改方案如下:
def create_app
app = Flask(__name__)
# 初始化数据库配置
db.init_app(app)
with app.app_context():
db.create_all()
### 注意:重点就在这里,需要加上下面这句代码
# 因为db.init_app(app)只是初始化db,所以还需要把app赋值给db
# 不然后续调用时会出现获取不到应用上下文app的情况
db.app = app
return app