按照我们在 How to关闭 MySQL 中的 sqlalchemy 连接,我正在检查 Sqlalchemy 在我的数据库中创建的连接,但我无法在不退出 Python 的情况下关闭它们.
如果我在 python 控制台中运行此代码,它会保持会话打开,直到我退出 python:
from sqlalchemy.orm import sessionmaker从模型导入 OneTable,get_engineengine = get_engine(database="mydb")session = sessionmaker(绑定=引擎)()结果 = session.query(OneTablepany_name).all()# 一些处理数据的工作 #session.close()我发现关闭它的唯一解决方法是在最后调用 engine.dispose().
根据我上面给出的链接中的评论,我现在的问题是:
- 为什么需要 engine.dispose() 来关闭会话?
- session.close() 还不够吗?
这里有一个关于会话"这个词的核心混淆.我在这里不确定,但看起来您可能将 SQLAlchemy Session 与MySQL @@session,指的是你第一次做一个连接到 MySQL 以及断开连接时.
这两个概念不一样.SQLAlchemy 会话通常表示在特定数据库连接上一个或多个事务的范围.
因此,按字面意思回答您的问题的答案是调用 session.close(),即如何正确关闭 SQLAlchemy 会话".
但是,您的问题的其余部分表明您想要一些功能,当特定的 Session 关闭时,您希望实际的 DBAPI 连接也关闭.
这基本上意味着您希望禁用连接池.正如其他答案提到的那样,很简单,使用 NullPool.>
Following what we commented in How to close sqlalchemy connection in MySQL, I am checking the connections that SQLAlchemy creates into my database and I cannot manage to close them without exiting from Python.
If I run this code in a python console, it keeps the session opened until I exit from python:
from sqlalchemy.orm import sessionmaker from models import OneTable, get_engine engine = get_engine(database="mydb") session = sessionmaker(bind=engine)() results = session.query(OneTablepany_name).all() # some work with the data # session.close()and the only workaround I found to close it is to call engine.dispose() at the end.
As per the comments in the link I gave above, my question are now:
- Why is engine.dispose() necessary to close sessions?
- Doesn't session.close() suffice?
There's a central confusion here over the word "session". I'm not sure here, but it appears like you may be confusing the SQLAlchemy Session with a MySQL @@session, which refers to the scope of when you first make a connection to MySQL and when you disconnect.
These two concepts are not the same. A SQLAlchemy Session generally represents the scope of one or more transactions, upon a particular database connection.
Therefore, the answer to your question as literally asked, is to call session.close(), that is, "how to properly close a SQLAlchemy session".
However, the rest of your question indicates you'd like some functionality whereby when a particular Session is closed, you'd like the actual DBAPI connection to be closed as well.
What this basically means is that you wish to disable connection pooling. Which as other answers mention, easy enough, use NullPool.
更多推荐
如何关闭 SQLAlchemy 会话?
发布评论