2016-10-26 22 views
0

什麼我打開我的SQLAlchemy的應用中的一些調試後注意到,就是這樣一個說法:SQLAlchemy的query.all()行爲

self.session.query(User).all()

似乎運行的每行一個查詢中桌子。

select * from user where id = 1

select * from user where id = 2

select * from user where id = n

我期望只發佈一個簡單的select * from user。這是預期的行爲還是在我的應用程序中配置不當?

+0

這不是預期的。請張貼您的模型配置。 – univerio

+0

同意。絕對沒有預料到。潛在的延遲加載關係的問題 – dizzyf

回答

0

所以,事實證明這與交易範圍和Flask_RESTPlus marshal_with裝飾者有關。我基本上這樣的:

@api.marshal_with(User) 
def get(self): 
    with transaction_scope(current_app.dbsession): 
     return self.user_service.get_users(), 200 

其中transaction_scope基本上作用域的交易與數據庫的交互。

但是,這導致修飾器嘗試編組響應超出事務範圍,因此它看到了過時的對象,並在處理它們時對其進行了補水處理,從而導致無數查詢。

我改成了這樣:

def get(self): 
    with transaction_scope(current_app.dbsession): 
     return api.marshal(self.user_service.get_users(), User), 200 

這解決了這個問題。

TL; DR - 在事務外運行時,marshal_with裝飾器有一些意外的行爲。