浏览之前,倡议先看这个参考文档:python 如何查看一个函数的参数
先来看看官网样例: Depends for function
https://fastapi.tiangolo.com/zh/tutorial/dependencies/#_3
如果是其余的呢?
比方如何给 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__
中
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__
中
仍然能够失常显示
以 fastapi_filter 举例
fastapi_filter:
- 官网:https://fastapi-filter.netlify.app/
- github 地址:https://github.com/arthurio/fastapi-filter
- pypi 地址:https://pypi.org/project/fastapi-filter/
fastapi_filter 用的是 class 计划,动静生成 class