from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/")
async def n(rule: Literal["1", "2", "3"] = Query(...)):
return rule
import uvicorn
uvicorn.run(app, port=8000)
这实际和pydantic也有关系
如上
curl -X 'GET' \
'http://localhost:8000/?rule=2' \
-H 'accept: application/json'
是可以正确请求并返回1
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/")
async def n(rule: Literal[1, 2, 3] = Query(...)):
return rule
import uvicorn
uvicorn.run(app, port=8000)
把str改成int
curl -X 'GET' \
'http://localhost:8000/?rule=1' \
-H 'accept: application/json'
结果返回错误
{
"detail": [
{
"type": "literal_error",
"loc": [
"query",
"rule"
],
"msg": "Input should be 1, 2 or 3",
"input": "1",
"ctx": {
"expected": "1, 2 or 3"
}
}
]
}
这就很奇怪了,它把他看成str而没有处理成为int再来检验
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/")
async def n(rule: int = Query(...)):
print(type(rule))
return rule
import uvicorn
uvicorn.run(app, port=8000)
这样的是没有问题,我们是知道的
fastapi = 0.115.12
pydantic = 2.7.4
python=3.11