gpt4 book ai didi

python - 我需要使用 SQLAlchemy session 吗?

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

SQLAlchemy 的官方教程提供了使用 session 系统的示例,例如:

>>> from sqlalchemy.orm import sessionmaker
>>> Session = sessionmaker(bind=engine)

许多非官方教程也使用 session ,但有些根本不使用它们,而是选择任何人称之为这种方法的方法:
e = create_engine('sqlite:///company.db')
conn = e.connect()
query = conn.execute("SELECT first_name FROM employee")

当这个更简单的系统似乎做同样的事情时,为什么还需要 session ?就我所见,官方文档并没有说明为什么这是必要的。

官方 SQLAlchemy 文档中有一个特别相关的部分:

A web application is the easiest case because such an application is already constructed around a single, consistent scope - this is the request, which represents an incoming request from a browser, the processing of that request to formulate a response, and finally the delivery of that response back to the client. Integrating web applications with the Session is then the straightforward task of linking the scope of the Session to that of the request. The Session can be established as the request begins, or using a lazy initialization pattern which establishes one as soon as it is needed. The request then proceeds, with some system in place where application logic can access the current Session in a manner associated with how the actual request object is accessed. As the request ends, the Session is torn down as well, usually through the usage of event hooks provided by the web framework. The transaction used by the Session may also be committed at this point, or alternatively the application may opt for an explicit commit pattern, only committing for those requests where one is warranted, but still always tearing down the Session unconditionally at the end.



...和...

Some web frameworks include infrastructure to assist in the task of aligning the lifespan of a Session with that of a web request. This includes products such as Flask-SQLAlchemy, for usage in conjunction with the Flask web framework, and Zope-SQLAlchemy, typically used with the Pyramid framework. SQLAlchemy recommends that these products be used as available.



不幸的是,我仍然无法确定是否需要使用 session ,或者最后一段是否暗示某些实现(例如 Flask-SQLAlchemy)已经在自动管理 session 。

我需要使用 session 吗?不使用 session 是否存在重大风险?我是否已经在使用 session ,因为我在使用 Flask-SQLAlchemy?

最佳答案

就像您指出的那样,如果您仅使用普通 SQLAlchemy Core 构造和执行查询,则 session 不是绝对必要的。 .但是,它们提供了利用 SQLAlchemy ORM 所需的更高抽象层。 . Session 维护修改后的模型图,并确保在必要时将更改高效且一致地刷新到数据库中。

由于您已经使用 Flask-SQLAlchemy,因此即使您不需要 ORM 功能,我也没有理由避免 session 。该扩展程序处理隔离请求所需的所有管道,因此您不必重新发明轮子并可以专注于您的应用程序代码。

关于python - 我需要使用 SQLAlchemy session 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43694859/

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