gpt4 book ai didi

python - SQLAlchemy的多线程使用

转载 作者:IT老高 更新时间:2023-10-28 20:36:49 27 4
gpt4 key购买 nike

我想制作一个用 Python 编写的数据库应用程序编程接口(interface),并使用 SQLAlchemy(或任何其他数据库连接器,如果被告知使用 SQLAlchemy 执行此类任务不是好方法)。设置是在 Linux 或 BSD 上运行的 MySQL 服务器和在 Linux 或 BSD 机器(外部或本地)上运行的 Python 软件。

基本上我想做的是为每个连接生成一个新线程,并且协议(protocol)将是自定义且非常简单的,尽管对于每个请求我想打开一个新事务(或我已阅读的 session )然后我需要提交 session 。我现在面临的问题是从另一个连接同时发生另一个 session 的可能性很高。

我的问题是我应该如何处理这种情况?

  • 我是否应该使用锁,以便只能同时运行一个 session ?
  • session 实际上是线程安全的,我认为它们不是线程安全的吗?
  • 有没有更好的方法来处理这种情况?
  • 线程是不可行的吗?

最佳答案

session 对象不是线程安全的,而是线程本地From the docs:

"The Session object is entirely designed to be used in a non-concurrent fashion, which in terms of multithreading means "only in one thread at a time" .. some process needs to be in place such that mutltiple calls across many threads don’t actually get a handle to the same session. We call this notion thread local storage."

如果您不想自己管理线程和 session ,SQLAlchemy 有 ScopedSession 对象来为您处理:

The ScopedSession object by default uses threading.local() as storage, so that a single Session is maintained for all who call upon the ScopedSession registry, but only within the scope of a single thread. Callers who call upon the registry in a different thread get a Session instance that is local to that other thread.

Using this technique, the ScopedSession provides a quick and relatively simple way of providing a single, global object in an application that is safe to be called upon from multiple threads.

参见 Contextual/Thread-local Sessions 中的示例用于设置您自己的线程安全 session :

# set up a scoped_session
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker

session_factory = sessionmaker(bind=some_engine)
Session = scoped_session(session_factory)

# now all calls to Session() will create a thread-local session
some_session = Session()

# you can now use some_session to run multiple queries, etc.
# remember to close it when you're finished!
Session.remove()

关于python - SQLAlchemy的多线程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6297404/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com