報錯信息部分截取: 錯誤根源: 排錯: 相信很多人都是這樣寫的init 文件的吧: 然後再叢manager啟動文件導入create_app 這樣寫了之後,那麼你就只能在視圖函數中執行資料庫操作了!!! 解決辦法: 方式一 直接實例化app 不要寫create_app函數了,在啟動文件中直接導入app ...
報錯信息部分截取:
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