I apologize if this has been answered. I’ve searched repeatedly over years and have yet to find an adequate solution to actually terminate a session on a postgresql 13 server made by my python scripts. A simple example:
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import sessionmaker
# Create engine
connection_string = v.connection_string
engine = create_engine(connection_string)
# Create a Session
Session = sessionmaker(bind=engine)
session = Session()
try:
# Use session connection
with session.connection() as connection:
connection.execute(text('DROP TABLE IF EXISTS
interim_schema.location;'))
session.commit()
except SQLAlchemyError as e:
print(f"Error occurred while executing SQL commands: {e}")
session.rollback()
finally:
session.close()
My understanding is this should completely close the session, but it doesn’t.
I’ve tried engine.dispose() but that just resets the connection pool. I’ve tried the recommended session as explained above which also does not terminate the session. I expect the database connection to vanish on the postresql server side.
2
Answers
It’s just an example. I suggest you to read more about
context manager
anddecorators
in python. It’s really helpful.Can you please provide some more information?
Also, enable the sqlalchemy engine echo logging feature:
For example, when I run very similar code to yours (I try to drop
"foo"
), I get the following output:Everything from
BEGIN (implicit)
and below is interesting and tells me that the program is not correctly configured. Please share more info and I can try to help you out.