从外部来源更改Django的设置 [英] Change Django's settings from an external source
问题描述
我想用Python编写脚本来编辑Django应用程序settings.py文件.除了将文件读取为文本文件之外,还有其他方法可以编辑设置文件中变量的值并保存吗?
I would like to write a script in Python to edit my Django application settings.py file. 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?
推荐答案
除了将文件读取为文本文件之外,还有其他方法可以编辑设置文件中变量的值并保存吗?
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.只需添加如下语句:
There is no need to parse & rewrite settings.py as such. Just add a statement like this:
import json
overrides = json.loads(open('settings.json').read())
globals().update(overrides)
然后
settings.json
包含如下设置:
{
"MY_SETTING" : "FOO"
}
我在这里以.json文件为例.只要 overrides
是字典,您就可以使用任何返回字典的源(例如yml,您自己的格式,甚至是python的类 __ dict __
).
I'm using a .json file here as an example. As long as overrides
is a dictionary, you can use any source that returns a dictionary (e.g. yml, your own format, or even a python's class __dict__
).
因此,从 django.conf
导入的 settings
将包含新设置,就如同直接在 settings.py
中指定的一样.:
As a result, settings
as imported from django.conf
will contain the new setting as if it was specified directly in settings.py
:
$ python manage.py shell
In [1]: print settings.MY_SETTING
FOO
这篇关于从外部来源更改Django的设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!