使用环境时 FastAPI 中需要 Pydantic 验证错误字段

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

我正在 YouTube 上的 FreeCodeCamp 上学习 Python API 开发课程,其中我们将一些静态值移至环境变量中。这是我在尝试重新加载应用程序时遇到的错误:

pydantic.error_wrappers.ValidationError: 8 validation errors for Settings
database_hostname
  field required (type=value_error.missing)
database_port
  field required (type=value_error.missing)
database_password
  field required (type=value_error.missing)
database_name
  field required (type=value_error.missing)
database_username
  field required (type=value_error.missing)
secret_key
  field required (type=value_error.missing)
algorithm
  field required (type=value_error.missing)
access_token_expire_minutes
  field required (type=value_error.missing)

这是我的架构(config.py):

class Settings(BaseSettings):
    database_hostname: str
    database_port: str
    database_password: str
    database_name: str
    database_username: str
    secret_key: str
    algorithm: str
    access_token_expire_minutes: int

    class Config:
        env_file = '../.env'

这是我的环境(.env):

DATABASE_HOSTNAME=localhost
DATABASE_PORT=5432
DATABASE_PASSWORD=password
DATABASE_NAME=fastapi
DATABASE_USERNAME=postgres
SECRET_KEY=123456789
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60

如何使我的 BaseSettings 类能够读取 .env 文件中的环境变量?

python api fastapi environment pydantic
2个回答
6
投票

我能够通过在项目中使用完整路径来解决该错误。我有主项目文件夹,其中有

.env
文件和
app
文件夹。我的 config.py 文件位于
app/
中,因此配置中的 env 文件的相对路径是
/../.env
:

不要忘记导入操作系统

class Settings(BaseSettings):
    database_hostname: str
    database_port: str
    database_password: str
    database_name: str
    database_username: str
    secret_key: str
    algorithm: str
    access_token_expire_minutes: int

    class Config:
        env_file = f"{os.path.dirname(os.path.abspath(__file__))}/../.env"

0
投票

试试这个

如果 .env 文件与您的主应用程序文件夹位于同一文件夹。

class Settings(BaseSettings):
    database_hostname: str
    database_port: str
    database_password: str
    database_name: str
    database_username: str
    secret_key: str
    algorithm: str
    access_token_expire_minutes: int

    class Config:
        env_file = '.env'
© www.soinside.com 2019 - 2024. All rights reserved.