为什么我们用yield 来用sqlalchemy 在Fastapi 中获取Sessionlocal?
Why we use yield to get Sessionlocal in Fastapi with sqlalchemy?
def get_db():
db = SessionLocal()
try:
return db
finally:
db.close()
我使用 Sqlalchemy 截断了这段代码以在 fastapi 中获取 Sessionlocal。好吧,当我使用 return 而不是 Yield 时。我的代码仍然有效。然后,我不明白使用 Yield 的原因。有人可以帮助我吗?
Well, when I used return instead of Yield. My code still works. Then, I do not understand the reason of using Yield.
这是一个很好的问题,答案是,是的,有理由使用 yield 而不是 return。
SQLAlchemy 默认有一个 Connection Pooling 机制。这意味着使用 yield 您将为每个请求创建一个会话。当您使用 return
时,您正在为所有应用程序使用单个数据库连接。
还不清楚吗?让我们想象一下,让事情变得更有趣。
那么我们在这个例子中有什么?
- 一个包含 5 个不同连接的连接池。
- 2 个端点
- 3 个传入请求。
当您使用 yield 时,它看起来像下面这样,因为它转到一个端点,向数据库请求一些东西,并且 yield 每次都会创建一个新的 Session 对象。它提供了围绕一系列操作的事务范围,但是在那里使用 return
而不是 yield
只会 return 该会话对象。
有一个根本的区别,当你使用 return
时,关闭是在 之前 函数 returns db
对象执行的,实际上您正在返回一个 closed db
对象。 Because
When return
passes control out of a try
statement with a finally
clause, that finally
clause is executed before really leaving the function.
否则,当使用yield
时,finally
代码块被执行在请求被处理并且响应已发送。您可以阅读有关 dependencies with yield here.
的更多信息
为什么你的代码继续工作,如果不查看整个代码我无法判断。
def get_db():
db = SessionLocal()
try:
return db
finally:
db.close()
我使用 Sqlalchemy 截断了这段代码以在 fastapi 中获取 Sessionlocal。好吧,当我使用 return 而不是 Yield 时。我的代码仍然有效。然后,我不明白使用 Yield 的原因。有人可以帮助我吗?
Well, when I used return instead of Yield. My code still works. Then, I do not understand the reason of using Yield.
这是一个很好的问题,答案是,是的,有理由使用 yield 而不是 return。
SQLAlchemy 默认有一个 Connection Pooling 机制。这意味着使用 yield 您将为每个请求创建一个会话。当您使用 return
时,您正在为所有应用程序使用单个数据库连接。
还不清楚吗?让我们想象一下,让事情变得更有趣。
那么我们在这个例子中有什么?
- 一个包含 5 个不同连接的连接池。
- 2 个端点
- 3 个传入请求。
当您使用 yield 时,它看起来像下面这样,因为它转到一个端点,向数据库请求一些东西,并且 yield 每次都会创建一个新的 Session 对象。它提供了围绕一系列操作的事务范围,但是在那里使用 return
而不是 yield
只会 return 该会话对象。
有一个根本的区别,当你使用 return
时,关闭是在 之前 函数 returns db
对象执行的,实际上您正在返回一个 closed db
对象。 Because
When
return
passes control out of atry
statement with afinally
clause, thatfinally
clause is executed before really leaving the function.
否则,当使用yield
时,finally
代码块被执行在请求被处理并且响应已发送。您可以阅读有关 dependencies with yield here.
为什么你的代码继续工作,如果不查看整个代码我无法判断。