我有以下代码片段对Customer表进行操作:
with session.begin(subtransactions=True):
db_obj = Customer(...)
result = io_processing() # may cause greenlet switching
# I do not want to make it inside the transaction above,
# Because some legacy I/O related code which will causes greenlet switching
if result:
self.read_write_db(session, db_obj)
在read_write_db函数中:
with session.begin(subtransactions=True):
# do some work on db_obj passed from outside
将事务外的'db_obj'传递给另一个函数是否安全?
或者我必须在read_write_db中再次查询db_obj并更新它?
答案 0 :(得分:0)
是的,这是可能的,但您必须通过在db_obj
的会话中合并read_write_db
来获取新实例。
with session.begin(subtransactions=True):
merged_db_obj = session.merge(db_obj)
# work with merged_db_obj ...
有关所有详细信息,请参阅http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#merging。合并可能很棘手。