SQLAlchemy 线程中的事务是否安全? [英] Are transactions in SQLAlchemy thread safe?

查看:42
本文介绍了SQLAlchemy 线程中的事务是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SQLAlchemy 的表达式语言而不是它的 orm 开发一个网络应用程序.我想在我的应用程序中使用多个线程,但我不确定线程​​安全.我正在使用 文档的这一部分来制作连接.我认为这是线程安全的,因为我在每个请求中都引用了一个特定的连接.这个线程安全吗?

解决方案

连接会话 表示既不是线程安全的,也不是打算在线程之间共享.

<块引用>

Connection 对象不是线程安全的.虽然可以使用正确同步的访问在线程之间共享连接,但底层 DBAPI 连接仍然可能不支持线程之间的共享访问.有关详细信息,请查看 DBAPI 文档.

<块引用>

Session 非常适合以非并发方式使用,这通常意味着一次只能在一个线程中使用.

应该以这样的方式使用 Session,即一个实例存在于单个事务中的单个系列操作.

更重要的一点是,您不应该希望使用具有多个并发线程的会话.

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

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

<块引用>

Web 请求和线程的这种简单对应意味着将 Session 与线程相关联意味着它也与在该线程中运行的 Web 请求相关联,反之亦然,前提是 Session 仅在 Web 请求开始后创建并在网络请求结束前拆除.

I am developing a web app using SQLAlchemy's expression language, not its orm. I want to use multiple threads in my app, but I'm not sure about thread safety. I am using this section of the documentation to make a connection. I think this is thread safe because I reference a specific connection in each request. Is this thread safe?

解决方案

The docs for connections and sessions say that neither is thread safe or intended to be shared between threads.

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.

There is no guarantee when using the same connection (and transaction context) in more than one thread that the behavior will be correct or consistent.

You should use one connection or session per thread. If you need guarantees about the data, you should set the isolation level for the engine or session. For web applications, SQLAlchemy suggests using one connection per request cycle.

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.

这篇关于SQLAlchemy 线程中的事务是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆