我有一些 FastAPI 应用程序:
from typing import Annotated
import uvicorn
from fastapi import FastAPI, Query
from pydantic import constr
app = FastAPI()
@app.get("search")
async def search(
partner_ids: Annotated[
constr(pattern="((^|[,])[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})+"),
Query(),
] = "ca930bc7-f4cf-4b10-9c6f-7db13b6ab4f0",
):
pass
if __name__ == "__main__":
uvicorn.run("uuid_list:app", reload=True, port=8004)
它的问题是
partner_ids
的验证不起作用:
同时regex101找到uuid:
FastAPI 有什么问题?
更新。正则表达式用于以逗号分隔的 uuid 列表。
正如@MatsLindh 在评论中提到的,你可以只使用
List[type]
。在你的情况下它将是:
@app.get("search")
async def search(
partner_ids: Annotated[List[UUID], Query(...)]
):
pass
它不会是逗号分隔的,但至少它是开箱即用的。
在您的示例中,您似乎在正则表达式中遇到了问题。尝试像这样设置 uuid 模式:
UUIDPattern = constr(
regex=r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
)
@app.get("/search")
async def search(
partner_ids: Annotated[List[UUIDPattern], Query()],
):
pass
但是您需要在方法本身中将其转换为实际的 uuid,因为它们将作为单个字符串传递。