加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

我是否需要使用SQLAlchemy会话?

发布时间:2020-12-20 13:17:26 所属栏目:Python 来源:网络整理
导读:SQLAlchemy的官方教程提供了使用会话系统的示例,如下所示: from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) 许多非官方教程也使用会话,但有些人根本没有使用它们,而是选择任何人称之为的方法: e = create_engine('sqlite://
SQLAlchemy的官方教程提供了使用会话系统的示例,如下所示:

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

许多非官方教程也使用会话,但有些人根本没有使用它们,而是选择任何人称之为的方法:

e = create_engine('sqlite:///company.db')
conn = e.connect()
query = conn.execute("SELECT first_name FROM employee")

当这个更简单的系统似乎做同样的事情时,为什么需要会话呢?官方文件并没有说清楚为什么这是必要的,据我所见.

官方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.

不幸的是,我仍然无法判断是否需要使用会话,或者最后一段是否暗示某些实现(如Flask-SQLAlchemy)已经自动管理会话.

我需要使用会话吗?不使用会话会有很大的风险吗?我已经在使用会话,因为我正在使用Flask-SQLAlchemy?

解决方法

正如您所指出的,如果您只使用普通 SQLAlchemy Core构造和执行查询,那么会话并不是绝对必要的.但是,它们提供了利用 SQLAlchemy ORM所需的更高抽象层.会话维护修改后的模型图并确保更改有效并在必要时始终刷新到数据库.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读