Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate sqlachemy session

I'm using sqlalchemy to store values in my database. I want to write test cases that can validate a session.

The code for getting a session object:

def get_session():
    Base = declarative_base()
    engine = create_engine('postgresql+psycopg2://testdb:hello@localhost/mydatabase')
    Base.metadata.bind = engine
    DBSession = sessionmaker(bind=engine)
    session = DBSession()
    return session

The problem is that even if I put a wrong database name, the above code still works. When I try to commit to database, then it throws an error(OperationalError).

How can I validate my session during its creation?

like image 846
user2430771 Avatar asked Aug 30 '25 17:08

user2430771


1 Answers

def validate(session):
    try:
        # Try to get the underlying session connection, If you can get it, its up
        connection = session.connection()
        return True
    except:
        return False
like image 181
Busturdust Avatar answered Sep 02 '25 10:09

Busturdust