它有时会发生在我的产品环境中(大多数时候都可以)。我怀疑它是否与 sessionmaker func 中的参数'expire_on_commit'有关
@close_session
def func():
session = DBSession() # scoped_session, thread_local
m = Model()
m.content = 'content'
session.add(m)
try:
session.commit()
except SQLAlchemyError as e:
session.rollback()
raise_my_exception()
return m.id
close_session 是一个装饰器,它将在“finally”部分执行“DBSession().close()”。ObjectDeleteError 发生在“return m.id”行
SQLAlchemy 配置:
engines = {
'master': create_engine(
settings.MASTER_URL, echo=settings.ECHO_SQL, pool_recycle=3600),
'slave': create_engine(
settings.SLAVE_URL, echo=settings.ECHO_SQL, pool_recycle=3600),
}
class RoutingSession(Session):
def get_bind(self, mapper=None, clause=None):
#return engines['master']
if self._flushing:
return engines['master']
else:
return engines['slave']
DBSession = scoped_session(sessionmaker(class_=RoutingSession))
ObjectDeletedError 文档:
class ObjectDeletedError(sqlalchemy.exc.InvalidRequestError)
| A refresh operation failed to retrieve the database
| row corresponding to an object's known primary key identity.
|
| A refresh operation proceeds when an expired attribute is
| accessed on an object, or when :meth:`.Query.get` is
| used to retrieve an object which is, upon retrieval, detected
| as expired. A SELECT is emitted for the target row
| based on primary key; if no row is returned, this
| exception is raised.
|
| The true meaning of this exception is simply that
| no row exists for the primary key identifier associated
| with a persistent object. The row may have been
| deleted, or in some cases the primary key updated
| to a new value, outside of the ORM's management of the target
| object.
|
编辑:我在“session.commit()”之后放置了“return m.id”,仍然引发了 ObjectDeletedEror
@close_session
def func():
session = DBSession() # scoped_session, thread_local
m = Model()
m.content = 'content'
session.add(m)
try:
session.commit()
return m.id
except SQLAlchemyError as e:
session.rollback()
raise_my_exception()
编辑2:
我更改了我的 RoutingSession 以仅返回 master 并且错误消失了:
class RoutingSession(Session):
def get_bind(self, mapper=None, clause=None):
return engines['master']
所以它必须与这个主/从配置有关。
关于如何解决它的任何想法?