Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask SqlAlchemy begin and end transaction

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.

like image 981
Ankit Avatar asked Aug 09 '15 21:08

Ankit


People also ask

How do I create a transaction in SQLAlchemy?

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.

What SQLAlchemy execute return?

SQLAlchemy execute() return ResultProxy as Tuple, not dict.

Does SQLAlchemy close connection automatically?

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.

What does flush do SQLAlchemy?

flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.


1 Answers

How do I do cancel the session/transaction in case of flask-sqlalchemy extension.

That's what db.session.rollback() does.

like image 191
Oin Avatar answered Oct 17 '22 11:10

Oin