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.
版权声明:本文标题:python - How to avoid redundant manual assignment of environment variables in Django settings? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743970961a2570688.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论