admin管理员组

文章数量:1356266

In my Django project, I store configuration variables in a .env file for security and flexibility. However, every time I introduce a new environment variable, I have to define it in two places: .env and settings.py.

As the project grows and the number of environment variables increases, settings.py become filled with redundant redefinition of what's already in .env.

Is there a way to automatically load all .env variables into Django's settings without manually reassigning each one? Ideally, I want any new variable added to .env to be instantly available from settings module without extra code.

What I can think of is something like:

from dotenv import dotenv_values

env_variables = dotenv_values(".envs")
globals().update(env_variables)

Or even something a little bit better to handle values of type list.

for key, value in env_variables.items():
    globals()[key] = value.split(",") if "," in value else value

# Ensure ALLOWED_HOSTS is always a list
ALLOWED_HOSTS = ALLOWED_HOSTS if isinstance(ALLOWED_HOSTS, list) else [ALLOWED_HOSTS]

But I do not like to mess around with globals(). Also, I'm not sure if this kind of variable management is a good idea, or if I should stick to my previous approach for better readability and to maintain a reference to each environment variable in the code.

本文标签: pythonHow to avoid redundant manual assignment of environment variables in Django settingsStack Overflow