简体   繁体   English

SQLAlchemy并发和查询

[英]SQLAlchemy Concurrency and Queries

I have a number of separate machines, each of which uses a separate instantiation of 我有很多单独的机器,每个机器都使用一个单独的实例

Session = scoped_session(sessionmaker(bind=engine)) . Session = scoped_session(sessionmaker(bind=engine))

If machine A runs the code 如果机器A运行代码

session = Session()
session.add(Foo(pk=1))
session.commit()

what do I have to do ensure that when machine B runs the below code... 我必须做的是确保机器B运行以下代码时...

session = Session()
result = session.query(Foo).get(1)

... that result holds the new row of Foo that machine A created (assume that machine A's code ran first). ... result将保留机器A创建的Foo的新行(假定机器A的代码先运行)。 I've had problems before where Session "A" commits an object but another Session "B" cannot find it in a query until I reinstantiate Session "B". 在会话“ A”提交对象之前,我遇到了问题,但是在重新实例化会话“ B”之前,另一个会话“ B”无法在查询中找到它。

scoped_session wraps Session in a thread local storage object; scoped_sessionSession包装在线程本地存储对象中; if you're doing more work to handle threads, you might want to either refactor your code to use a single scoped_session instance for all threads, or use the result of sessionmaker directly, without wrapping it, again one for all threads, and call Session() for each thread. 如果您需要做更多的工作来处理线程,则可能需要重构代码以对所有线程使用单个scoped_session实例,或者直接将sessionmaker的结果(不包装它)再次用于所有线程,然后调用Session()每个线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM