简体   繁体   English

如何在 python 点环境文件中定义列表?

[英]How to define lists in python dot env file?

In Fast API documentation it is recommended to use.env to load the config.在 Fast API 文档中,建议使用 .env 加载配置。 Only that it only supports string as far as I understand it.据我所知,只是它只支持字符串。

from fastapi import FastAPI
from pydantic import BaseSettings


class Settings(BaseSettings):
    api_tokens = []

    class Config:
        env_file = ".env"


settings = Settings()
app = FastAPI()

I usually change the API tokens every few months, by adding a new one to the list and after some time I remove the older ones.我通常每隔几个月更改一次 API 令牌,方法是在列表中添加一个新令牌,一段时间后我删除旧令牌。 That gives the users enough time to upgrade to latest edition without any disruption.这使用户有足够的时间升级到最新版本而不会受到任何干扰。 In the meanwhile both API tokens will be valid for some time.同时,两个 API 令牌将在一段时间内有效。

But I can't define a list in the .env file.但我无法在.env文件中定义列表。

API_TOKENS = abc123,abc321

Am I missing something?我错过了什么吗?

UPDATE:更新:

It actually is possible.其实是可以的。 The answer below is correct, however I still had to change the type like this:下面的答案是正确的,但是我仍然不得不像这样更改类型:

class Settings(BaseSettings):
    api_tokens: list

You can use json module to convert string variable to a list in python.您可以使用 json 模块将字符串变量转换为 python 中的列表。

.env file .env 文件

LIST_VAR='["Foo", "bar"]'

Python code Python 代码

import os
import json
from dotenv import load_dotenv
load_dotenv()
list_var = json.loads(os.environ['LIST_VAR'])

This should work,这应该工作,

API_TOKENS = ["abc123","abc321"]

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

相关问题 如何在测试期间覆盖“env_file”? - How to override "env_file" during tests? 如何通过命令行将 env 文件传递给 FastAPI 应用程序 - How to pass env file to FastAPI app via command line 无法配置 Starlette.env 文件 - Can not configure a Starlette .env file 如何在 Python3/Pydantic 中定义具有互斥成员/字段的 class - How to define a class with mutually exclusive members/fields in Python3/Pydantic Pydantic 设置管理 + FastAPI:如何在 pytest 测试期间忽略 a.env 文件? - Pydantic settings management + FastAPI: how to ignore a .env file during tests with pytest? 如何在 fastAPI 中定义 REST 端点<input type="file"> (并使它与角度一起工作)? - How to define a REST endpoint in fastAPI for <input type="file"> (and make it work with angular)? 在 Python 请求 GET 中发送列表和字典 - Send lists and dictionaries in Python requests GET 我应该如何在 Optional[] 中定义创建子可选模型,使用 FastAPI python 的输入和 pydantic 库? - How shall i define create sub-optional models in Optional[] working with typing and pydantic libs for FastAPI python? 具有本地 ENV 文件的 BaseSettings 模型的 Pydantic 验证错误 - Pydantic validation error for BaseSettings model with local ENV file 如何使用 github 操作在 aws sam 中获取 s3 env 文件 - How to get s3 env files in aws sam with github action
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM