python – SQLAlchemy线程中的事务是否安全?

我正在使用SQLAlchemy的表达式语言开发一个Web应用程序,而不是它的orm.我想在我的应用程序中使用多个线程,但我不确定线程​​安全性.我正在使用
this section of the documentation进行连接.我认为这是线程安全的,因为我在每个请求中引用了一个特定的连接.这个线程安全吗? 最佳答案
connections
sessions的文档说,线程不是线程安全的,也不打算在线程之间共享.

The Connection object is not thread-safe. While a Connection can be shared among threads using properly synchronized access, it is still possible that the underlying DBAPI connection may not support shared access between threads. Check the DBAPI documentation for details.

The Session is very much intended to be used in a non-concurrent fashion, which usually means in only one thread at a time.

The Session should be used in such a way that one instance exists for a single series of operations within a single transaction.

The bigger point is that you should not want to use the session with multiple concurrent threads.

在多个线程中使用相同的连接(和事务上下文)时,无法保证行为正确或一致.

您应该为每个线程使用一个连接或会话.如果需要保证数据,则应设置引擎或会话的隔离级别.对于Web应用程序,SQLAlchemy suggests每个请求周期使用一个连接.

This simple correspondence of web request and thread means that to associate a Session with a thread implies it is also associated with the web request running within that thread, and vice versa, provided that the Session is created only after the web request begins and torn down just before the web request ends.

点赞