什么时候使用 `session_maker` 什么时候在 sqlalchemy 中使用 `Session`

When to use `session_maker` and when to use `Session` in sqlalchemy

Sqlalchemy's documentation 表示可以通过两种方式创建会话:

from sqlalchemy.orm import Session
session = Session(engine)

或与 sessionmaker

from sqlalchemy.orm import session_maker
Session = session_maker(engine)
session = Session()

现在无论哪种情况都需要一个全局对象(引擎或 session_maker 对象)。所以我真的不明白 session_maker 的意义是什么。可能是我理解错了。

我找不到任何建议何时应该使用其中一种。所以问题是:在哪种情况下您想使用 Session(engine),在哪种情况下您更喜欢 session_maker

docs 很好地描述了差异:

Session is a regular Python class which can be directly instantiated. However, to standardize how sessions are configured and acquired, the sessionmaker class 通常用于创建顶级会话配置,然后可以在整个应用程序中使用该配置,而无需重复配置参数。