In Fast API documentation it is recommended to use.env to load the config. 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. 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.
But I can't define a list in the .env
file.
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.
.env file
LIST_VAR='["Foo", "bar"]'
Python code
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"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.