I'm writing a SqlAlchemy transaction in flask using sqlalchemy extension:
flask.ext.sqlalchemy
Here's how my code looks like:
def charge_user(user):
db.session.begin()
try:
transaction = create_transaction()
if not transaction:
// cancel the session
return False
db.session.add(transaction)
user.paid = True
db.session.add(user)
return True
except Exception:
db.session.rollback()
return False
Just one quick question, the documentation of sqlalchemy extension vs the flask-sqlalchemy plugin are very confusing. How do I do cancel the session/transaction in case of flask-sqlalchemy extension.
connection() method at the start of a transaction: from sqlalchemy. orm import Session # assume session just constructed sess = Session(bind=engine) # call connection() with options before any other operations proceed. # this will procure a new connection from the bound engine and begin a real # database transaction.
SQLAlchemy execute() return ResultProxy as Tuple, not dict.
connect() method returns a Connection object, and by using it in a Python context manager (e.g. the with: statement) the Connection. close() method is automatically invoked at the end of the block.
flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.
How do I do cancel the session/transaction in case of flask-sqlalchemy extension.
That's what db.session.rollback()
does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With