gpt4 book ai didi

python - 为什么必须调用 db.session.remove()?

转载 作者:太空狗 更新时间:2023-10-29 21:21:51 29 4
gpt4 key购买 nike

我正在按照教程学习 flask web 开发,这是它的单元测试文件:

import unittest
from flask import current_app
from app import create_app, db

class BasicsTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()

def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()

def test_foo(self):
pass

此外,我在 SQLAlchemy document 中找到了这些句子:

Using the above flow, the process of integrating the Session with the web application has exactly two requirements:

  • ......

  • Ensure that scoped_session.remove() is called when the web request ends, usually by integrating with the web framework’s event system to establish an “on request end” event.

我的问题是:为什么我需要调用 db.session.remove()

我认为只要 db.session.commit() 没有被调用,数据库就不会被修改。另外,当我注释掉这一行时,应用程序仍然能够通过单元测试。

我查阅了Flask-SQLAlchemy和SQLAlchemy的文档,前者连db.session.remove()都没有,后者太抽象了,看不懂.

最佳答案

Using the above flow, the process of integrating the Session with the web application has exactly two requirements:

  • ......
  • Ensure that scoped_session.remove() is called when the web request ends, usually by integrating with the web framework’s event system to establish an “on request end” event.

SQLAlchemy 中,提到上述操作是因为 Web 应用程序中的 session 应该是作用域,这意味着每个请求处理程序都创建和销毁自己的 session 。

这是必要的,因为 Web 服务器可以是多线程的,因此可以同时处理多个请求,每个请求处理不同的数据库 session 。

Flask-SQLAlchemy 很好地处理了这个场景,它为每个请求创建一个全新的或新的作用域 session 。如果你进一步挖掘它,你会发现 here ,它还在 app.teardown_appcontext(对于 Flask >=0.9)、app.teardown_request(对于 Flask 0.7-0.8)、app.after_request(对于 Flask <0.7),这里是它调用 db.session.remove() 的地方。

测试 环境不会完全复制真实请求的环境,因为它不会推送/弹出应用程序上下文。因此, session 永远不会在请求结束时被删除。

作为旁注,请记住在调用 client.get() 时也不会调用使用 before_requestafter_request 注册的函数>.

您可以通过对测试进行小的更改来强制应用程序上下文自动推送和弹出,而不是手动推送 setUp() 并在 tearDown() 中弹出:

def test_foo(self):
with app.app_context():
client = app.test_client()
# do testing here for your endpoints

通过此更改,无需手动编写 db.session.remove() 即可通过测试。

Flask-Testing 的文档似乎是错误的或者更可能是过时的。也许事情在某些时候像他们描述的那样工作,但这对于当前的 Flask 和 Flask-SQLAlchemy 版本来说并不准确。

希望对您有所帮助!

关于python - 为什么必须调用 db.session.remove()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39480914/

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