python - 从外部源更改 Django 的设置

标签 python django django-settings

我想用 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/

相关文章:

python - 在 Python 模块中排序

远程服务器上的 Django 教程 : how to view in my browser?

django - 使用 Django 和 Redis 的简单事件提要

python - 着色 Voronoi 图

python - 重置 Python/Matplotlib 中绘图的默认字体/颜色

django - 难以覆盖 Django Admin 模板

带有单独凭证文件的 Django PostgreSQL 设置?

css - Django 在生产中找不到通过 CSS 文件链接的图像

python - 为什么这两个看似等价的表达式求值不同?

python - 如何在 Django 1.5 中使用 'User' 作为外键