Skip to content

Python: Django and FastAPI without python-dotenv files

Django settings and FastAPI's pydantic-settings already prefer real environment variables. Start them with npx getmyenv run and delete the .env file.

Oct 10, 2026 · 5 min read

An encrypted padlock leads to one terminal command, which starts a Django or FastAPI app and then Gunicorn on a server.
One getmyenv run command starts Django or FastAPI. On the server, systemd runs the same command.

Why your code stays the same

  • Django does not read .env files. Settings read os.environ.
  • python-dotenv's load_dotenv() skips names that are already set, unless you pass override=True.
  • pydantic-settings ranks environment variables above the env_file. A missing file is ignored.
  • uvicorn --env-file calls load_dotenv(), so the same rule applies.

1. Move the values out of .env

bash
npx getmyenv import rm .env

Existing load_dotenv() calls can stay. With the file gone, they load nothing. Delete it, or a name missing from getmyenv falls back to the old file value without a warning.

run refuses names that change how Python starts, like PYTHONPATH. PYTHONUNBUFFERED and PYTHONDONTWRITEBYTECODE are allowed. Keep the others out of the context.

2. Django

python
# settings.py import os SECRET_KEY = os.environ["DJANGO_SECRET_KEY"] DEBUG = os.environ.get("DJANGO_DEBUG") == "1"
bash
npx getmyenv run -- python manage.py runserver npx getmyenv run -- python manage.py migrate

3. FastAPI

python
# settings.py from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(env_file=".env") database_url: str settings = Settings()
bash
npx getmyenv run -- uvicorn main:app --reload

database_url comes from DATABASE_URL in the environment. Values passed to Settings(...) in code still win over both.

4. Gunicorn under systemd

On the server, the token goes in a file only root can read. Wrap the start command in ExecStart. Use full paths: systemd's PATH does not include your virtualenv, and Node and npx must be installed.

# /etc/systemd/system/mysite.service
[Service]
User=mysite
WorkingDirectory=/srv/mysite
EnvironmentFile=/etc/mysite/getmyenv.env
ExecStart=/usr/bin/npx getmyenv run production -- /srv/mysite/.venv/bin/gunicorn mysite.wsgi
Restart=on-failure

/etc/mysite/getmyenv.env holds one line, GETMYENV_TOKEN=..., a server token for Production. For FastAPI, put uvicorn main:app --workers 4 from the virtualenv after -- instead.

With Ask me, the first start waits for your approval on Requests. journalctl -u mysite shows the link. More on servers: /docs/machine-access. Other languages: /docs/languages.

Related docs: Languages, How run works, Machine access