依赖注入系统的简单性使得 FastAPI 兼容:
from typing import Optional
# 1、编写依赖项
async def common_parameters(q: Optional[str] = None,
skip: int = 0,
limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
from typing import Optional
# 2、导入 Depends
from fastapi import Depends
# 1、编写依赖项函数
async def common_parameters(q: Optional[str] = None,
skip: int = 0,
limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog: https://www.cnblogs.com/poloyy/
# time: 2021/9/24 1:08 下午
# file: 25_dependency.py
"""
from typing import Optional, Dict, Any
# 2、导入 Depends
from fastapi import Depends, FastAPI
import uvicorn
app = FastAPI()
# 1、编写依赖项函数
async def common_parameters(q: Optional[str] = None,
skip: int = 0,
limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
# 3、编写路径操作函数,参数声明为 Depends
@app.get("/items")
async def read_items(commons: Dict[str, Any] = Depends(common_parameters)):
return commons
if __name__ == "__main__":
uvicorn.run(app="25_dependency:app", host="127.0.0.1", port=8080, reload=True, debug=True)
Depends(common_parameters)
直接在 Swagger API 文档上测试了,顺便看看长啥样
即使是依赖项,FastAPI 也会对它做数据验证,不符合类型则报错
# 非 async 依赖项
def test_dep(name: str):
return name
# async 路径操作函数
@app.get("/name")
async def test_name(name: str = Depends(test_dep)):
return name
# async 依赖项
async def test_user_info(info: dict):
return info
# 非 async 路径操作函数
@app.get("/info")
def test_info(info: dict = Depends(test_user_info)):
return info
from typing import Optional, Dict, Any
# 2、导入 Depends
from fastapi import Depends, FastAPI
import uvicorn
app = FastAPI()
# 1、编写依赖项
async def common_parameters(*,
q: Optional[str] = None,
skip: int = 0,
limit: int = 100,
# 新增一个 Dict 类型的参数
info: Dict[str, Any]):
return {"q": q, "skip": skip, "limit": limit, "info": info}
# 3、编写路径操作函数,参数声明为 Depends
@app.get("/items")
async def read_items(commons: Dict[str, Any] = Depends(common_parameters)):
return commons
if __name__ == "__main__":
uvicorn.run(app="25_dependency:app", host="127.0.0.1", port=8080, reload=True, debug=True)