我是否需要使用SQLAlchemy会话?

我是否需要使用SQLAlchemy会话?,第1张

概述SQLAlchemy的官方教程提供了使用会话系统的示例,如下所示: >>> from sqlalchemy.orm import sessionmaker>>> Session = sessionmaker(bind=engine) 许多非官方教程也使用会话,但有些人根本没有使用它们,而是选择任何人称之为的方法: e = create_engine('sqlite:///company.db') 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功能,我也没有理由避免会话.扩展程序处理隔离请求所需的所有管道,因此您不必重新发明轮子并可以专注于您的应用程序代码.

总结

以上是内存溢出为你收集整理的我是否需要使用SQLAlchemy会话?全部内容,希望文章能够帮你解决我是否需要使用SQLAlchemy会话?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1196296.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存