上下文管理器

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

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

 

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

 

FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
    





            
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
# 自定义上下文管理器
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
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
    





            
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 

 

FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
    





            
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
async def get_db():
    # 1、创建数据库连接对象
    db = DBSession()
    try:
        # 2、返回数据库连接对象,注入到路径操作装饰器 / 路径操作函数 / 其他依赖项
        yield db

  # 响应传递后执行 yield 后面的代码
    finally: # 确保后面的代码一定会执行

        # 3、用完之后再关闭
        db.close()
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
    





            
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 

 

上下文管理器

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

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

 

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

 

FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
    





            
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
# 自定义上下文管理器
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
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
    





            
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 

 

FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
    





            
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
async def get_db():
    # 1、创建数据库连接对象
    db = DBSession()
    try:
        # 2、返回数据库连接对象,注入到路径操作装饰器 / 路径操作函数 / 其他依赖项
        yield db

  # 响应传递后执行 yield 后面的代码
    finally: # 确保后面的代码一定会执行

        # 3、用完之后再关闭
        db.close()
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 
    





            
FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 

 

相关文章:

  • 2022-01-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-02
  • 2021-11-22
  • 2021-09-18
猜你喜欢
  • 2021-12-31
  • 2021-07-11
  • 2021-12-31
  • 2021-09-27
  • 2021-10-31
  • 2022-12-23
  • 2021-09-10
相关资源
相似解决方案