我想用 Python 编写一个脚本来编辑我的 Django 应用程序 settings.py 文件。除了将文件作为文本文件读取之外,还有其他方法可以编辑设置文件中的变量值并保存吗?
最佳答案
other than reading the file as a text file is there any other way I can edit the values of the variables in the settings file and save it?
不需要像这样解析和重写settings.py。只需添加这样的语句:
import json
overrides = json.loads(open('settings.json').read())
globals().update(overrides)
settings.json
然后包含您的设置,如下所示:
{
"MY_SETTING" : "FOO"
}
我在这里使用 .json 文件作为示例。只要 overrides
是字典,您就可以使用任何返回字典的源(例如 yml、您自己的格式,甚至是 Python 的类 __dict__
)。
因此,从 django.conf
导入的 settings
将包含新设置,就像直接在 settings.py
中指定一样:
$ python manage.py shell
In [1]: print settings.MY_SETTING
FOO
关于python - 从外部源更改 Django 的设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32946157/