【问题标题】:Define a Request parameter as an optional variable type in fastapi在 fastapi 中将请求参数定义为可选变量类型
【发布时间】:2021-12-03 12:21:27
【问题描述】:

我想在 fastapi 中将 Request 对象定义为可选变量类型,但出现错误

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],但仍然显示相同的错误消息。

【问题讨论】:

  • 可选的request 字段是什么意思?将请求视为首先需要调用路由器;你想达到什么目标?

标签: python fastapi python-typing typing pydantic


【解决方案1】:

如果您想添加可选的查询参数,您可以简单地将它们声明为处理端点的(路径操作)函数的参数(参见FastAPI docs),例如:

@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 docs 中描述的方法,例如:

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>

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 2017-07-28
    • 2020-02-20
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多