gpt4 book ai didi

python - 如何彻底拆除数据库连接和 session ?

转载 作者:行者123 更新时间:2023-11-29 12:09:57 25 4
gpt4 key购买 nike

当根据请求拆卸 sqlalchemy 连接时,以下是当前代码:

def init_request():
engine = craete_engine(url)
session = sessionmaker(bind=engine, autoflush=False)

def teardown():
session.close()
engine.dispose()

即使在session.close()之后也应该调用engine.dispose()吗?我不知道 session.close() 真的意味着拆除数据库连接。但是关于engine.dispose(),这个处理只是连接池而不是连接(写在文档上) http://docs.sqlalchemy.org/en/latest/core/connections.html

最佳答案

关闭 session 会删除所有连接资源并将它们返回到池中,请参阅 here .

The close() method issues a expunge_all(), and releases any transactional/connection resources. When connections are returned to the connection pool, transactional state is rolled back as well.

如果您没有执行任何额外操作,create_engine 将建立一个连接池,请参阅 here .

The Engine returned by the create_engine() function in most cases has a QueuePool integrated, pre-configured with reasonable pooling defaults.

如果您想在 session 关闭后释放连接(顺便说一句,我想知道为什么?),我建议您改为禁用池(相同链接,下面几段);这样您就可以避免每次都创建引擎。

Disabling pooling using NullPool:

from sqlalchemy.pool import NullPool
engine = create_engine(
'postgresql+psycopg2://scott:tiger@localhost/test',
poolclass=NullPool)

关于python - 如何彻底拆除数据库连接和 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30864902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com