我有一个问题,我使用SQLAlchemy / Tastypie REST接口插入数据库项目,但随后获取项目列表时该项目丢失。它仅在我第二次获得项目列表后才会显示。
我正在使用 SQLAlchemy 和通过 mod_wsgi 在 Apache 上运行的 Tastypie/Django。我使用单例数据库管理器类来保存我的引擎和 declarative_base,并使用 Tastypie,一个单独的类来获取会话并确保在提交出现问题时回滚。在下面的更新中,当我在插入后没有关闭会话时会出现问题。 为什么这是必要的?
我的原始代码是这样的:
Session = scoped_session(sessionmaker(autoflush=True))
# Singleton Database Manager class for managing session
class DatabaseManager():
engine = None
base = None
def ready(self):
host='mysql+mysqldb://etc...'
if self.engine and self.base:
return True
else:
try:
self.engine = create_engine(host, pool_recycle=3600)
self.base = declarative_base(bind=self.engine)
return True
except:
return False
def getSession(self):
if self.ready():
session = Session()
session.configure(bind=self.engine)
return session
else:
return None
DM = DatabaseManager()
# A session class I use with Tastypie to ensure the session is destroyed at the
# end of the transaction, because Tastypie creates singleton Resources used for
# all threads
class MySession:
def __init__(self):
self.s = DM.getSession()
def safeCommit(self):
try:
self.s.commit()
except:
self.s.rollback()
raise
def __del__(self):
try:
self.s.commit()
except:
self.s.rollback()
raise
# ... Then ... when I get requests through Apache/mod_wsgi/Django/Tastypie
# First Request
obj_create():
db = MySession()
print db.s.query(DBClass).count() # returns 4
newItem = DBClass()
db.s.add(newItem)
db.s.safeCommit()
print db.s.query(DBClass).count() # returns 5
# Second Request after First Request returns
obj_get_list():
db = MySession()
print db.s.query(DBClass).count() # returns 4 ... should be 5
# Third Request is okay
obj_get_list():
db = MySession()
print db.s.query(DBClass).count() # returns 5
更新
经过进一步挖掘,问题似乎是我的会话需要在创建后关闭。也许是因为 Tastypie 的 object_create() 将 SQLAlchemy 对象添加到它的包中,而我不知道它离开函数范围后会发生什么:
obj_create():
db = MySession()
newItem = DBClass()
db.s.add(newItem)
db.s.safeCommit()
copiedObj = copyObj(newItem) # copy SQLAlchemy record into non-sa object (see below)
db.s.close()
return copiedObj
如果有人愿意在答案中解释这一点,我可以关闭这个问题。另外,对于那些好奇的人,我将我的对象从 SQLAlchemy 中复制出来,如下所示:
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
class MyTastypieResource(Resource):
...
def copyObject(self, object):
base = {}
# self._meta is part of my tastypie resource
for p in class_mapper(self._meta.object_class).iterate_properties:
if p.key not in base and p.key not in self._meta.excludes:
base[p.key] = getattr(object,p.key)
return Struct(**base)