阅读之前,建议先看这个参考文档: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
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
相关推荐: 从0搭建Vue3组件库(十):如何搭建一个 Cli 脚手架
本篇文章将实现一个名为create-easyest脚手架的开发,只需一个命令npm init easyest就可以将整个组件库开发框架拉到本地。 创建 Cli 包 首先,我们在 packages 目录下新建 cli 目录,同执行pnpm init进行初始化,然…