postgresql Python sqlalchemy完全正确终止会话

olqngx59  于 2023-06-29  发布在  PostgreSQL
关注(0)|答案(2)|浏览(179)

我很抱歉,如果这已经得到了回答。多年来我一直在反复寻找,但还没有找到一个合适的解决方案来实际终止我的python脚本在postgresql13服务器上创建的会话。一个简单的例子:

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()

我的理解是这应该完全关闭会话,但它没有。
我尝试了engine.dispose(),但它只是重置了连接池。我已经尝试了如上所述的推荐会话,它也不会终止会话。我希望数据库连接在postresql服务器端消失。

i1icjdpr

i1icjdpr1#

这只是个例子我建议你阅读更多关于context managerdecorators在python中的内容。真的很有帮助

from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, declarative_base, sessionmaker

class SqlAlchemy:
    def __init__(self, database_url: str):
        self.engine = create_engine(database_url, echo=False)
        self.session = sessionmaker(self.engine)
        self.base = declarative_base()

@contextmanager
def in_transaction(session) -> Session:
    session = session()
    session.begin()
    try:
        yield session
        session.commit()
    except BaseException:
        session.rollback()
        raise
    finally:
        session.close()

db = SqlAlchemy('your database url')

def db_session(db):
    with in_transaction(db.session) as session:
        yield session
        
        
# example function where you need session
@db_session
def my_function(session):
    session.execute('SQL for example:)')
k0pti3hp

k0pti3hp2#

你能提供更多的信息吗?

  • 您使用哪些信息来确定会话已关闭?
  • 如果有的话,你的程序有什么输出?(例如错误消息或SQL语句)
  • 否则代码会工作吗?即,表是否成功删除?

另外,启用 sqlalchemy engine echo logging功能:

engine = create_engine(connection_string, echo=True)

例如,当我运行与你的代码非常相似的代码时(我试图删除"foo"),我得到以下输出:

2023-06-28 08:26:03,673 INFO sqlalchemy.engine.Engine select pg_catalog.version()
2023-06-28 08:26:03,673 INFO sqlalchemy.engine.Engine [raw sql] {}
2023-06-28 08:26:03,674 INFO sqlalchemy.engine.Engine select current_schema()
2023-06-28 08:26:03,674 INFO sqlalchemy.engine.Engine [raw sql] {}
2023-06-28 08:26:03,679 INFO sqlalchemy.engine.Engine show standard_conforming_strings
2023-06-28 08:26:03,679 INFO sqlalchemy.engine.Engine [raw sql] {}
2023-06-28 08:26:03,686 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-06-28 08:26:03,686 INFO sqlalchemy.engine.Engine DROP TABLE IF EXISTS foo;
2023-06-28 08:26:03,686 INFO sqlalchemy.engine.Engine [generated in 0.00021s] {}
2023-06-28 08:26:03,688 INFO sqlalchemy.engine.Engine ROLLBACK
Error occurred while executing SQL commands: This transaction is inactive
/home/nchappell/programming/py/foo/foo.py:21: SAWarning: transaction already deassociated from connection
  session.rollback()

BEGIN (implicit)及以下的一切都很有趣,并告诉我程序配置不正确。请分享更多信息,我可以尝试帮助你。

相关问题