Python (FastAPI / Flask) .env Generator
Modern Python services (FastAPI, Flask, litestar) all consume .env via python-dotenv or Pydantic's BaseSettings. This generator produces a .env with the idiomatic keys — SECRET_KEY, DATABASE_URL, REDIS_URL, ALLOWED_ORIGINS.
ENVIRONMENT=development LOG_LEVEL=INFO DATABASE_URL=postgresql://user:pass@localhost:5432/app REDIS_URL=redis://localhost:6379/0 SECRET_KEY=F8j0j-ZfsM_Ns1DliPFw7Bzb_A7TSpwOLvv0T-eonlWlDJnT8FDBqOCbiA3gYYx9 ALLOWED_ORIGINS=http://localhost:3000 SENTRY_DSN=
Secrets regenerate on every page load. Want to combine stacks? Use the full generator.
How to use this .env in Python (FastAPI / Flask)
- 1.Save the output as .env in the project root.
- 2.Install python-dotenv: pip install python-dotenv (or pydantic-settings for Pydantic).
- 3.Load at startup: from dotenv import load_dotenv; load_dotenv() — before importing settings.
- 4.In FastAPI, prefer Pydantic's BaseSettings for automatic validation + type coercion.
Gotchas
- ⚠Pydantic BaseSettings reads env at class-init time, not at runtime — changes need a restart.
- ⚠Don't use os.getenv() inside request handlers — read once at startup, pass via dependency injection.
- ⚠ALLOWED_ORIGINS from .env is a string; split on ',' in settings.py, not at the read site.
Common keys explained
ENVIRONMENTdevelopment | staging | production. Controls logging verbosity.
LOG_LEVELDEBUG | INFO | WARNING | ERROR. Standard Python logging levels.
DATABASE_URLPostgres URL parsed by SQLAlchemy or asyncpg.
REDIS_URLRedis for cache + Celery broker.
SECRET_KEYServer signing key. Generate — never type manually.
ALLOWED_ORIGINSComma-separated CORS origins.
Loading and validating the .env in Python (FastAPI / Flask)
# pip install pydantic-settings (FastAPI's recommended way)
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
database_url: str # required -> ValidationError if missing
secret_key: str
debug: bool = False # "true"/"1"/"yes" parsed correctly
allowed_origins: list[str] = [] # JSON in .env: ["https://a.com"]
settings = Settings()
# Flask / scripts: pip install python-dotenv
# from dotenv import load_dotenv; load_dotenv()Python (FastAPI / Flask): env vars in development, staging and production
python-dotenv and pydantic-settings both give real environment variables priority over the .env file. In Docker or on a PaaS you set variables on the container, and the same code picks them up without any .env present.
Flask reads .flaskenv and .env automatically when python-dotenv is installed and you use the flask command. Under gunicorn or uwsgi it does not, so call load_dotenv() yourself or set the variables in the process manager.
Python (FastAPI / Flask): .env errors and fixes
pydantic_core.ValidationError: Field required [type=missing]A required setting has no value. The field name maps to the upper-case variable: database_url reads DATABASE_URL. Check that the .env path is relative to the working directory.
os.getenv('DEBUG') == 'False' is still truthyEnvironment values are strings. Parse them: debug = os.getenv('DEBUG', 'false').lower() in ('1', 'true', 'yes'), or let pydantic-settings cast to bool.
load_dotenv() returns FalseNo .env was found. Pass an explicit path: load_dotenv(Path(__file__).parent / '.env'), or use find_dotenv().
Python (FastAPI / Flask) .env FAQ
python-dotenv or pydantic-settings?
python-dotenv just loads the file into os.environ. pydantic-settings also validates and casts types and fails at startup when something is missing. For FastAPI and larger apps, use pydantic-settings.
Does load_dotenv() override existing variables?
No, not by default. Pass override=True to make the .env win, which is rarely what you want in production.
How do I store a list in a .env file?
Use a comma-separated string and split it, or a JSON array that pydantic-settings parses for list fields: ALLOWED_ORIGINS=["https://a.com","https://b.com"].