pythonfastapipydanticpython-dotenv

How to define lists in python dot env file?


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

Solution

  • This should work,

    API_TOKENS = ["abc123","abc321"]