Flask中无法在其他函数中查询Sqlachemy的解决办法

时间:2021-08-03 12:33:50

报错信息部分截取:

 File "D:\python 3.5\lib\site-packages\flask_sqlalchemy\__init__.py", line 912, in get_app
    'No application found. Either work inside a view function or push'
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

错误根源:

class GroupForm(FlaskForm):
    '''分组表单'''
    menu_id = SelectField(label = "所属菜单",validators = [DataRequired("请选择菜单!")],coerce = int,
                         choices = [(v.id,v.name) for v in Menu.query.all()],render_kw = {"class":"form-control"})
#在form表单中执行了数据库查询操作,就会出现报错,后面发现只有在视图函数中执行数据库查询操作才不会报错(出了视图函数外的其他地方都不好使)                      

排错:

相信很多人都是这样写的init 文件的吧:

from flask_sqlalchemy import SQLAlchemy
from flask import Flask
from config import Config
db = SQLAlchemy()
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    Config.init_app(app)
    db.init_app (app)
    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint,url_prefix = '/admin')
    return app

然后再丛manager启动文件导入create_app

from flask_script import Manager
from app import create_app,db
app = create_app()
from flask_migrate import MigrateCommand,Migrate
manage = Manager(app)
migrate = Migrate(app,db)
manage.add_command('db',MigrateCommand)
if __name__ == '__main__':
    app.run()

这样写了之后,那么你就只能在视图函数中执行数据库操作了!!!

解决办法:

方式一 直接实例化app 不要写create_app函数了,在启动文件中直接导入app对象:

from flask_sqlalchemy import SQLAlchemy
from flask import Flask
app = Flask(__name__)
from config import Config
app.config.from_object(Config)
Config.init_app(app)
db = SQLAlchemy(app)
from .models import Auth,Role,User,Group,Menu

from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint,url_prefix = '/admin')

方式二 如果你要你的表单中使用数据库查询,那么可以换种方式已达到同样的效果

class GroupForm(FlaskForm):
    '''分组表单'''
    menu_id = SelectField(label = "所属菜单",validators = [DataRequired("请选择菜单!")],coerce = int,
                         choices = "",render_kw = {"class":"form-control"})

#然后在你的视图函数中实例化这个Form 类的时候给它赋值
    form = MenuForm()
    if request.method == "GET":
        form.menu_id.choices = [(v.id,v.name) for v in Menu.query.all ()]

#或者你也可以在你的Form类中写一个init方法
class GroupForm(FlaskForm):
    '''分组表单'''
     menu_id = SelectField(label = "所属菜单",validators = [DataRequired("请选择菜单!")],coerce = int,
                         choices = "",render_kw = {"class":"form-control"})

     def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.menu_id.choices = [(v.id,v.name) for v in Menu.query.all()]
        

问题解决

转自:https://blog.csdn.net/zhongqiushen/article/details/79162792