据我了解,对于标准的 MySQLdb 驱动程序,您通常使用 with 语句来确保使用 __exit__ 关闭连接。
SQLAlchemy sessions 或 engine 是否需要等效的 with 语句?或者手动超时关闭连接是否足以满足 SQLAlchemy 的需求?
请您参考如下方法:
这是来自文档的引用:
Most web frameworks include infrastructure to establish a single Session, associated with the request, which is correctly constructed and torn down corresponding torn down at the end of a request. Such infrastructure pieces include products such as Flask-SQLAlchemy, for usage in conjunction with the Flask web framework, and Zope-SQLAlchemy, for usage in conjunction with the Pyramid and Zope frameworks. SQLAlchemy strongly recommends that these products be used as available.
In those situations where integration libraries are not available, SQLAlchemy includes its own “helper” class known as scoped_session.
所以,看起来像 scoped_session是你在说什么。 Documentation关于如何使用作用域 session 非常好。基本上,您定义何时打开 session 以及何时关闭它(参见 Using Custom Created Scopes ):
from my_web_framework import get_current_request, on_request_end
from sqlalchemy.orm import scoped_session, sessionmaker
Session = scoped_session(sessionmaker(bind=some_engine), scopefunc=get_current_request)
@on_request_end
def remove_session(req):
Session.remove()
希望对您有所帮助。
