简体   繁体   中英

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. I am not sure if I created the connections/sessions/transactions properly. Any pointers?

使您的事务隔离级别可序列化,或通过query.with_lockmode('update')获取记录以进行更新。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM