user2430771
user2430771

Reputation: 1422

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?

Upvotes: 3

Views: 2606

Answers (1)

Busturdust
Busturdust

Reputation: 2495

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

Upvotes: 1

Related Questions