什么是 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()