当类型定义为 str | 时,FastAPI 将布尔值强制转换为字符串布尔

问题描述 投票:0回答:1

当使用

main.py
config.py
运行我的代码时,我将
config.testing
返回为
str
而不是
bool

此处的仓库/分支:https://github.com/dycw/tutorial-test-driven-development-with-fastapi-and-docker/blob/getting-started/

或有来源

# src/app/main.py

from fastapi import Depends, FastAPI

from app.config import Settings, get_settings

app = FastAPI()


@app.get("/ping")
async def pong(*, settings: Settings = Depends(get_settings)) -> dict[str, str | bool]:
    return {
        "ping": "pong!",
        "environment": settings.environment,
        "testing": settings.testing,
    }
# src/app/config.py

from functools import lru_cache
from logging import getLogger
from typing import cast

from pydantic import BaseSettings

_LOGGER = getLogger("uvicorn")


class Settings(BaseSettings):
    environment: str = "dev"
    testing: bool = cast(bool, 0)


@lru_cache
def get_settings() -> Settings:
    _LOGGER.info("Loading config settings from the environment...")
    return Settings()

我的 JSON 返回:

enter image description here

python fastapi pydantic
1个回答
0
投票

您的代码看起来与我今天在教程中看到的有点不同,但我的代码返回一个不带引号的

false
值。对我来说相关的行是 config.py 中的
testing: bool = 0

我建议查看本教程的当前版本并更新您的代码以使其看起来像现在的样子。

© www.soinside.com 2019 - 2024. All rights reserved.