【问题标题】:I wanted to understand what this yield does我想了解这个产量的作用
【发布时间】:2022-11-02 05:49:12
【问题描述】:

我想了解这个产量的作用。在我找到的示例中,我总是看到这种类型的代码,但我不明白它与普通实例有什么不同

def get_db():
  db = SessionLocal()
  try:
    yield db
  finally:
    db.close()

此示例在 FastAPI 文档中:https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/

【问题讨论】:

  • 这回答了你的问题了吗? What does the "yield" keyword do?
  • 我看过几个使用数组的例子,但是这段代码不是这样,我不明白这个yield在做什么,它只是一个数据库会话
  • 该示例确实 async def get_db(): - async 部分是有道理的。但是您引用的页面对您为什么这样做有很长的解释。通过在try 中执行yield,代码保证finally 子句(关闭数据库)始终运行,即使出现异常也是如此。
  • yield 允许依赖项在请求完成后运行额外的代码,例如进行一些额外的清理,例如关闭不再需要的任何延迟数据库连接(如给定示例中)或删除临时文件。
  • 这是一个context manager(Python 的一个术语)实现,可帮助您在退出上下文之前自动关闭连接。

标签: python sqlalchemy generator fastapi yield


【解决方案1】:

yield 是一个类似于 return 的关键字,除了函数将返回一个生成器。

快速示例:

def fun(num):
    for i in range(num):
        yield i
x = fun(5)
print(x)
# <generator object create_generator at 0xb7555c34>
for object in x:
    print(object)

"""
expected output:
        0
        1
        2
        3
        4
"""

you can checkout [this link][1] to read more


  [1]: https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do

在您的示例中,代码试图将数据库作为对象返回,如果失败则关闭它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    相关资源
    最近更新 更多