[英]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.