阅读之前,建议先看这个参考文档:python 如何查看一个函数的参数

先来看看官方样例: Depends for function

https://fastapi.tiangolo.com/zh/tutorial/dependencies/#_3

图片.png

如果是其他的呢?
比如如何给 Depends 传递的是:

  • class?
  • classs instance?

Depends for class

from typing import Any, Optional, List
import uvicorn
from fastapi import FastAPI, Form, Query, Depends
from fastapi import Depends

app = FastAPI()


class AddressFilter():
    def __init__(self, school: str | None = None) -> None:
        pass


@app.get('/')
async def list_object(
    address_filter: AddressFilter = Depends(AddressFilter),
):
    return {}


if __name__ == "__main__":

    uvicorn.run(
        app='api:app',
        host="127.0.0.1",
        port=9950,
        workers=1,
        reload=True
    )

把需要让 openAPI 显示的字段,添加在 class 的 __init__

图片.png

Depends for class instance

from typing import Any, Optional, List
import uvicorn
from fastapi import FastAPI, Form, Query, Depends
from fastapi import Depends

app = FastAPI()


class AddressFilter():
    def __call__(self, school: str | None = None, grade: int = 1) -> None:
        pass


af = AddressFilter()


@app.get('/')
async def list_object(
    address_filter: AddressFilter = Depends(af),
):
    return {}


if __name__ == "__main__":

    uvicorn.run(
        app='api:app',
        host="127.0.0.1",
        port=9950,
        workers=1,
        reload=True
    )

把需要让 openAPI 显示的字段,添加在 class instance 的 __call__

依然可以正常显示

图片.png

以 fastapi_filter 举例

fastapi_filter:

fastapi_filter 用的是 class 方案,动态生成 class

动态生成

可以配合 pydantic 的 create_model 实现

示例代码:

import inspect
from pydantic import BaseModel, create_model

# 使用 create_model 创建模型类
Person = create_model(
    "Person",
    name=(str, ...),  # 字段名称和类型
    age=(int, ...),   # 字段名称和类型
    email=(str, None)  # 字段名称和类型,可选字段
)

# 创建模型类的实例
# person = Person(name="John Doe", age=30, email="johndoe@example.com")

# # 打印模型实例的属性值
# print(person.name)
# print(person.age)
# print(person.email)


# def my_function(arg1, arg2, *, kwarg1="default", kwarg2="default"):
#     pass


# 使用inspect.signature获取函数的签名对象
sig = inspect.signature(Person)

# 打印函数的参数信息
for name, param in sig.parameters.items():
    print(f"Parameter: {name}")
    print(f"  Default value: {param.default}")
    print(f"  Annotation: {param.annotation}")
    print(f"  Kind: {param.kind}")
    print(f"  Required: {param.default == param.empty}")
    print()

fastapi_filter 也是通过 pydantic 的 create_model 这样实现的


universe_king
3.4k 声望680 粉丝