Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask sqlalchemy check whether object in db.session and ready for commit

I have objects which are newly created. I would like to know how can check whether current session has that object or not?

Something like this:

user = User(...)
....
db.session.add(user)
...
if db.session.has_object(user):
    <process further>

Is something like this possible?

Also, I would like to create after_request for my flask instance so that instead of bothering about commit, it will allow me to only check whether the db.session is ready for commit or not. If it is then execute db.session.commit().

Something like this:

@app.after_request
def after_request(response):
    if db.session.is_ready():
        db.session.commit()
like image 321
Rahul Shelke Avatar asked Oct 30 '14 14:10

Rahul Shelke


People also ask

What does DB Create_all () do?

create_all() function to create the tables that are associated with your models. In this case you only have one model, which means that the function call will only create one table in your database: from app import db, Student. db.

What is Session commit SQLAlchemy?

Session. commit() is used to commit the current transaction. It always issues Session. flush() beforehand to flush any remaining state to the database; this is independent of the “autoflush” setting.

What is Sessionmaker in SQLAlchemy?

Session in SQLAlchemy ORM However, to standardize how sessions are configured and acquired, the sessionmaker class is normally used to create a top-level Session configuration which can then be used throughout an application without the need to repeat the configurational arguments.


1 Answers

You can inspect the object to see it's current state. If it's been added to the session, but not yet flushed to the database, it's going to have a pending status, for example:

from sqlalchemy import inspect

u = User(name='Alice')
inspection = inspect(u)
inspection.pending  # False

db.session.add(u)
inspection.pending # True

db.session.commit()
inspection.pending # False

There's a little intro to the object states in the docs.

like image 189
Doobeh Avatar answered Sep 18 '22 12:09

Doobeh