終極解決:No application found. Either work inside a view function or push an application context.


在使用flask sqlalchemy的時候,提示錯誤:No application found. Either work inside a view function or push an application context.

 

 即意味着每一次操作數據庫的時候都需要用with語句來開篇,寫起來實在不太方便,有沒有什么一勞永逸的方式可以支持這里更高效的處理呢?

def sqlalchemy_context():
def add_context(func):
@wraps(func)
def do_job(*args, **kwargs):
from manage import app
# app.app_context().push()
with app.app_context():
result = func(*args,**kwargs)
return result
return do_job
return add_context

一個裝飾器即可,接下來在每一個需要對數據庫做出增刪改查處理的地方引用即可

如:

 
         
from sqlalchemy import and_,or_
from app.main import db
from app.main.model.user import User
from app.main import sqlalchemy_context

@sqlalchemy_context()
def get_all_users(): return User.query.filter_by(is_active=1).all()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM