gpt4 book ai didi

python - 如何在 SQLAlchemy for PostgreSQL 中设置事务隔离级别?

转载 作者:太空狗 更新时间:2023-10-29 18:31:56 29 4
gpt4 key购买 nike

我们正在使用 SQLAlchemy 声明性基础,我有一个方法,我想为其隔离事务级别。解释一下,有两个进程同时写入数据库,我必须让它们在一个事务中执行它们的逻辑。默认事务隔离级别是 READ COMMITTED,但我需要能够使用 SERIALIZABLE 隔离级别执行一段代码。

这是如何使用 SQLAlchemy 完成的?现在,我的模型中基本上有一个方法,它继承自 SQLAlchemy 的声明性基础,本质上需要以事务方式调用。

from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from psycopg2.extensions import ISOLATION_LEVEL_READ_COMMITTED
from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE

class OurClass(SQLAlchemyBaseModel):

@classmethod
def set_isolation_level(cls, level=ISOLATION_LEVEL_SERIALIZABLE):
cls.get_engine().connect().connection.set_isolation_level(level)

@classmethod
def find_or_create(cls, **kwargs):
try:
return cls.query().filter_by(**kwargs).one()
except NoResultFound:
x = cls(**kwargs)
x.save()
return x

我这样做是为了使用事务隔离级别调用它,但它没有按照我的预期进行。从我在 postgres 日志中看到的,隔离级别仍然是 READ COMMITTED。有人可以帮助确定我做错了什么吗?

我正在使用 SQLAlchemy 0.5.5

class Foo(OurClass):

def insert_this(self, kwarg1=value1):
# I am trying to set the isolation level to SERIALIZABLE
try:
self.set_isolation_level()
with Session.begin():
self.find_or_create(kwarg1=value1)
except Exception: # if any exception is thrown...
print "I caught an expection."
print sys.exc_info()
finally:
# Make the isolation level back to READ COMMITTED
self.set_isolation_level(ISOLATION_LEVEL_READ_COMMITTED)

最佳答案

来自 SQLAlchemy 的维护者 Michael Bayer:

Please use the "isolation_level" argument to create_engine() and use the latest tip of SQLAlchemy until 0.6.4 is released, as there was a psycopg2-specific bug fixed recently regarding isolation level.

The approach you have below does not affect the same connection which is later used for querying - you'd instead use a PoolListener that sets up set_isolation_level on all connections as they are created.

关于python - 如何在 SQLAlchemy for PostgreSQL 中设置事务隔离级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3518863/

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