简体   繁体   English

如何在 pydantic model for fastapi 中允许 List 作为查询参数而不是 requestbody

[英]How to allow List as query params instead of requestbody in pydantic model for fastapi

So I have a simple fastapi model as follows:所以我有一个简单的 fastapi model 如下:

 from typing import List
 
 from fastapi import Query, Depends, FastAPI
 from pydantic import BaseModel
 
 class QueryParams(BaseModel):
     req1: float = Query(...)
     opt1: int = Query(None)
     req_list: List[str] = Query(...)
 
 
 app = FastAPI()
 @app.post("/test", response_model=QueryParams)
 def foo(q: QueryParams = Depends()):
     return q

which works with the following command: curl -X "POST" "http://localhost:8000/test?req1=1" -d '{["foo"]}'使用以下命令: curl -X "POST" "http://localhost:8000/test?req1=1" -d '{["foo"]}'

However: I need it to work additionally with allowing the params in the uri request as such: curl -X "POST" "http://localhost:8000/test?req1=1&req_list=foo"但是:我需要它额外允许uri请求中的参数,例如: curl -X "POST" "http://localhost:8000/test?req1=1&req_list=foo"

I know that if I took out the req_list from the BaseModel, and shoved it in the function header as such我知道如果我从 BaseModel 中取出req_list ,并将其推入 function header 中

 from typing import List
 
 from fastapi import Query, Depends, FastAPI
 from pydantic import BaseModel
 
 class QueryParams(BaseModel):
     req1: float = Query(...)
     opt1: int = Query(None)
 
 
 app = FastAPI()
 @app.post("/test", response_model=QueryParams)
 def foo(q: QueryParams = Depends(), req_list: List[str] = Query(...)):
     return q

that it would work, but is there any way to keep it in the basemodel?它会起作用,但有什么方法可以将它保存在基本模型中?

Well I figured it out:好吧,我想通了:

 from typing import List
 
 from fastapi import Query, Depends, FastAPI
 from pydantic.dataclasses import dataclass
 
 @dataclass
 class QueryParams:
     req1: float = Query(...)
     opt1: int = Query(None)
     req_list: List[str] = Query(...)
 
 
 app = FastAPI()
 @app.post("/test", response_model=QueryParams)
 def foo(q: QueryParams = Depends()):
     return q

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM