flask踩坑记录:‘No application found. Either work inside a view function or push‘

全部异常堆栈:

flask踩坑记录:‘No application found. Either work inside a view function or push‘_第1张图片

异常堆栈分析:

从最后的'No application found. Either work inside a view function or push'看出这是flask_sqlalchemy抛出的异常:没有找到应用,需要在视图函数中或者压入到应用上下文中。

百度了一手才知道这是因为sqlalchemy运行时脱离的上下文环境。如果sqlalchemy的对象是在flask视图函数中工作,是会处于上下文环境,但我是在视图函数外使用的sqlalchemy对象。

flask踩坑记录:‘No application found. Either work inside a view function or push‘_第2张图片

在导入视图时,引用视图外的方法,方法里使用了sqlalchemy对象

flask踩坑记录:‘No application found. Either work inside a view function or push‘_第3张图片

原本是想在这里查询数据库记录的当前访问数据库类型,用来判断要返回的SQL是适用MySQL的还是适用Oracle的,没想到却出了这么个错误。

解决思路:

既然知道了错误是因为导入时sqlalchemy脱离了上下文导致的,那只要在上下文环境中进行导入应该就可以了。

flask踩坑记录:‘No application found. Either work inside a view function or push‘_第4张图片

测试结果:

flask踩坑记录:‘No application found. Either work inside a view function or push‘_第5张图片

已经能正常返回预期结果了。

以上解决思路参考了以下文章,如有不详尽之处请移步看下寻找灵感:

No application found. Either work inside a view function or push an application context.

数据插入异常 无上下文No application found. Either work inside a view function or push an application context.

虽然解决了报错,但是原本在SQL类里先获取适用的数据库类型的方式有点呆,这样每个实例对象都要访问一下数据库。准备改为使用flask钩子函数,在第一次请求视图时,把当前使用的数据库类型记录到app配置中去。

 

你可能感兴趣的:(flask,python,flask,sqlalchemy)