zoukankan      html  css  js  c++  java
  • FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器

    什么是 Context Manager

    上下文管理器

    在 Python 中,是可以在 with 语句中使用的任何 Python 对象,比如通过 with 来读取文件

    with open("./somefile.txt") as f:
        contents = f.read()
        print(contents)
    • 通过 open("./somefile.txt") 创建的对象就称为上下文管理器
    • 当 with 代码块执行完后,它可以确保关闭文件,即使有异常也是如此
    • 上下文管理器详细教程

    依赖项中使用 yield

    当使用 yield 创建依赖项时,FastAPI 会在内部将其转换为上下文管理器,并将其与其他一些相关工具结合起来

    在依赖项中使用上下文管理器与 yield

    # 自定义上下文管理器
    class MySuperContextManager:
    
        def __init__(self):
            self.db = DBSession()
    
        def __enter__(self):
            return self.db
    
        def __exit__(self, exc_type, exc_value, traceback):
            self.db.close()
    
    
    async def get_db():
        with MySuperContextManager() as db:
            yield db

    等价的普通写法

    async def get_db():
        # 1、创建数据库连接对象
        db = DBSession()
        try:
            # 2、返回数据库连接对象,注入到路径操作装饰器 / 路径操作函数 / 其他依赖项
            yield db
    
      # 响应传递后执行 yield 后面的代码
        finally: # 确保后面的代码一定会执行
    
            # 3、用完之后再关闭
            db.close()
  • 相关阅读:
    [Swift]LeetCode900. RLE 迭代器 | RLE Iterator
    TNS-12508 When Issuing Any SET Command For The Listene
    shell getopts
    archive log full ora-00257
    php 验证码
    php 缩略图
    弧度
    php输出中文字符
    流程图
    windows clone 迁移数据库
  • 原文地址:https://www.cnblogs.com/poloyy/p/15334686.html
Copyright © 2011-2022 走看看