我想实现以下目标:
- 我的应用程序包含一些“子域”,它们对应于应用程序的不同部分。
- 每个域都有自己的实体
- 我想像这样写一个 Controller :
@app.get("/{domain}/entity/{entity}/{id}")
async def read_users(domain: Domain, entity: Entity, id: Int):
pass
考虑 Entity
将是一个可以根据所选域更改的枚举。
例如,如果域是“架构”,则实体可以定义为:
class Entity(str, Enum):
building = "building"
floor = "floor"
但如果所选域是“车辆”,则匹配的实体将是:
class Entity(str, Enum):
engine = "engine"
wheels = "wheels"
更一般地说,我想我正在寻找的是一种使路径参数验证依赖于另一个路径参数的方法。
这样:
GET/architecture/entity/floor/1
是有效的,因为floor
是域architecture
的有效实体
GET/vehicle/entity/wheels/5
是有效的,因为wheels
是域vehicle
的有效实体
GET/architecture/entity/engine/1
无效,因为engine
不是域architecture
的有效实体
有什么办法可以实现吗?
最佳答案
您可以使用闭包。为简洁起见,以下代码未使用枚举:
from fastapi import FastAPI
app = FastAPI()
domains = {"architecture": ["building","floor"], "vehicle": ["engine","wheels"]}
def set_route(domain,entity):
url = "/{}/entity/{}/{{id}}".format(domain,entity)
@app.get(url)
async def read_users(id: int):
return(f"Users of the {domain} {entity} #{id}")
for domain, entities in domains.items():
for entity in entities:
set_route(domain,entity)
关于python - FastAPI动态多路径参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69160177/