python - FastAPI动态多路径参数

标签 python url fastapi pydantic

我想实现以下目标:

  • 我的应用程序包含一些“子域”,它们对应于应用程序的不同部分。
  • 每个域都有自己的实体
  • 我想像这样写一个 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)

它会生成所需的 API 架构: API Schema

关于python - FastAPI动态多路径参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69160177/

相关文章:

Javascript:使用正则表达式验证网站 URL

iphone - 在 iPhone 中显示从 ALAsset 检索到的 URL 中的图像

openapi - OpenAPI 中正则表达式 "pattern"的共同点是什么?

python - 是否可以自动合并本体,以便将精确匹配合并到一个首选术语下?

python - 模块 'tensorflow' 没有属性 'constant'

php - 通过 PHP 更改 URL

python - 为什么在 pod 中运行 python 文件与直接运行它的行为不同?

python - 如何使用 Python Selenium 拖放文件?

python - 如何使用 PySide2 实现响应式画廊 View

python - Fastapi 响应 - 反斜杠