Reputation: 26
I need to do the sequential steps:
How can I do that in SQLAlchemy, Flask, PostgreSQL? What ways are correct?
Upvotes: 0
Views: 622
Reputation: 311
I'm using Flask-Sqlalchemy, so try to make adjustments.
You can use with_for_update() here. docs
An example would be.
class TestTable(db.Model):
__tablename__ = "test_table"
id = Column(db.Integer(), primary_key=True)
filename = Column(db.String(1024))
is_complete = Column(db.Boolean(), default=False, server_default="f")
You can lock them by doing:
for table in TestTable.query.with_for_update().filter_by(is_complete=False).all():
# Example Check condition
if table.filename != 'bar' and table.id >= 10:
# Add a new row
newtable = TestTable(filename='foo')
db.session.add(newtable)
# Save and release lock
db.session.commit()
Upvotes: 1
Reputation: 248305
If you want that to be safe from race conditions, you need to use a transaction with SERIALIZABLE
isolation level. Perform the whole operation in that transaction.
Upvotes: 0