[英]SQLAlchemy(Postgres) and transaction
I want a record from a table(queue) to be selected, locked(no other process can edit this record) and updated at a later point in time. 我希望从表(队列)中选择一条记录,将其锁定(没有其他进程可以编辑此记录)并在以后的某个时间点进行更新。
I assumed if I put the whole querying and updating in a transaction, no other process can edit/query the same record. 我假设如果将整个查询和更新都放在事务中,那么其他任何进程都无法编辑/查询同一条记录。 But I am not quite able to achieve this. 但是我不太能够实现这一目标。
def move(one, two):
from settings import DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import create_engine
engine = create_engine('postgres://%s:%s@%s:%s/%s' % (DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME), echo = False)
conn = engine.connect()
tran = conn.begin()
Session = scoped_session(sessionmaker())
session = Session(bind=conn)
url = session.query(URLQueue).filter(URLQueue.status == one).first()
print "Got record: " + str(url.urlqueue_id)
time.sleep(5)
url.status = two
session.merge(url)
session.close()
tran.commit()
move('START', 'WIP')
If I start 2 process, they both update the same record. 如果我开始2进程,它们都将更新同一条记录。 I am not sure if I created the connections/sessions/transactions properly. 我不确定是否正确创建了连接/会话/事务。 Any pointers? 有指针吗?
使您的事务隔离级别可序列化,或通过query.with_lockmode('update')获取记录以进行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.