如何在快速 API Python 中阅读 URL 参数和正文输入
How to Read URL param and body typing in Fast API Python
我想在 Fast API Python 中创建一个通用端点定义,它读取 URL 路径参数,然后调用一个特定的方法来进行去实现。
但我总是得到
422 Unprocessable Entity
所以我希望它能像这样工作:
/answer/aaa -> handle_generic_answer -> read_item_aaa,将 body 键入 ModelAAA
/answer/bbb -> handle_generic_answer -> read_item_bbb,将 body 键入 ModelBBB
等等
这是通用端点代码:
@app.post("/answer/{type}")
def handle_generic_answer(type: str, item):
# I also tried
# def handle_generic_answer(type: str, item: Any):
# or
# def handle_generic_answer(type: str, item: Optional):
switcher = {
'aaaa': read_item_aaa,
'bbb': read_item_bbb,
'nothing': unrecognised_answer
}
func = switcher.get(type, unrecognised_answer)
print('answer >> ' + type)
func(item)
然后我根据 type
值调用单独的方法:
def read_item_aaa(item: ModelAAA):
update_aaa(item)
return {"type": "aaa", "result": "success"}
def read_item_bbb(item: ModelBBB):
update_bbb(item)
return {"type": "bbb", "result": "success"}
和一个默认值 -
def unrecognised_answer(type):
print("unrecognised_answer")
raise HTTPException(status_code=400, detail="answer type not found")
return {}
模型定义如下:
from pydantic import BaseModel, Field
class ModelAAA(BaseModel):
field1: str
field2: list = []
但我是否打电话
http://localhost:8000/answer/aaa
或http://localhost:8000/answer/some-other-url
我总是得到 422:
{
"detail": [
{
"loc": [
"query",
"item"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
您忘记注释正文参数 item
。
没有这个 item
被视为查询 str
参数。例如:
@app.post("/answer/{type}")
def handle_generic_answer(type: str, item: Union[ModelAAA, ModelBBB]):
我想在 Fast API Python 中创建一个通用端点定义,它读取 URL 路径参数,然后调用一个特定的方法来进行去实现。 但我总是得到
422 Unprocessable Entity
所以我希望它能像这样工作:
/answer/aaa -> handle_generic_answer -> read_item_aaa,将 body 键入 ModelAAA
/answer/bbb -> handle_generic_answer -> read_item_bbb,将 body 键入 ModelBBB 等等
这是通用端点代码:
@app.post("/answer/{type}")
def handle_generic_answer(type: str, item):
# I also tried
# def handle_generic_answer(type: str, item: Any):
# or
# def handle_generic_answer(type: str, item: Optional):
switcher = {
'aaaa': read_item_aaa,
'bbb': read_item_bbb,
'nothing': unrecognised_answer
}
func = switcher.get(type, unrecognised_answer)
print('answer >> ' + type)
func(item)
然后我根据 type
值调用单独的方法:
def read_item_aaa(item: ModelAAA):
update_aaa(item)
return {"type": "aaa", "result": "success"}
def read_item_bbb(item: ModelBBB):
update_bbb(item)
return {"type": "bbb", "result": "success"}
和一个默认值 -
def unrecognised_answer(type):
print("unrecognised_answer")
raise HTTPException(status_code=400, detail="answer type not found")
return {}
模型定义如下:
from pydantic import BaseModel, Field
class ModelAAA(BaseModel):
field1: str
field2: list = []
但我是否打电话
http://localhost:8000/answer/aaa
或http://localhost:8000/answer/some-other-url
我总是得到 422:
{
"detail": [
{
"loc": [
"query",
"item"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
您忘记注释正文参数 item
。
没有这个 item
被视为查询 str
参数。例如:
@app.post("/answer/{type}")
def handle_generic_answer(type: str, item: Union[ModelAAA, ModelBBB]):