1. 程式人生 > >Flask 報錯 RuntimeError: No application found. Either work inside a view function or push an applicati

Flask 報錯 RuntimeError: No application found. Either work inside a view function or push an applicati

報錯資訊部分擷取:

  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):
        self.menu_id.choices = [(v.id,v.name) for v in Menu.query.all()]
        super().__init__(*args,**kwargs)

問題解決