我想将Request
对象定义为FastAPI中的可选变量类型,但我得到了一个错误:
fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that typing.Optional[starlette.requests.Request] is a valid pydantic field type
代码如下:
from fastapi import APIRouter, Request
from typing import Optional, Union
import starlette
router = APIRouter(
tags=['pcinfo'],
prefix='/api/v1',
responses={404: {'message': 'Not found'}}
)
@router.get('/pcinfo/', tags=['pcinfo'])
def get_users(req: Optional[Request] = None):
if req:
print(type(req))
print(req.query_params)
para = dict(req.query_params)
return para
else:
print(req)
return {'message': 'hello'}
然后导入starlette
并将Optional[Request]
更改为Optional[starlette.requests.Request]
,但它仍然显示相同的错误信息。
如果您想添加可选的查询参数,您可以简单地将它们声明为处理端点的(路径操作)函数的参数(参见FastAPI文档),例如:
@router.get('/pcinfo/', tags=['pcinfo'])
def get_users(
query_param_1: Optional[int] = None,
query_param_2: Optional[str] = None,
):
if query_param_1:
print(query_param_1)
if query_param_2:
print(query_param_2)
if query_param_1 or query_param_2:
return {
"query_param_1": query_param_1,
"query_param_2": query_param_2,
}
if not query_param_1 and not query_param_2:
return {'message': 'hello'}
如果你想获得一个dict
的查询参数,你可以按照FastAPI文档中描述的方法,例如:
async def query_params(param1: Optional[int] = None, param2: Optional[str] = None):
return {"param1": param1, "param2": param2}
@router.get('/pcinfo/', tags=['pcinfo'])
def get_users(query_params: dict = Depends(query_params)):
if query_params["param1"]:
print(query_params["param1"])
if query_params["param2"]:
print(query_params["param2"])
# <your logic here>
您可以像下面这样将请求对象作为可选对象传递
import starlette
@app.api_route("/endpoint/v1/{my_id}", methods=["GET", "POST", "DELETE"])
async def myFunction(request : starlette.requests.Request = None):