Change django's settings from an external source

£可爱£侵袭症+ 提交于 2020-05-13 14:43:30

问题


I would like to write a script in python to edit my django app settigs.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?


回答1:


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?

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 then contains your settings like this:

{
  "MY_SETTING" : "FOO"
}

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__).

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 



回答2:


You want something like django-appconf.




回答3:


Inside your primary settings.py you can do something like the following:

from portal.base.settings import add_portal_settings
globals().update(add_portal_settings(locals()))

The content of portal.base.settings is something like:

def add_portal_settings(settings):
  settings['PORTAL_URL'] = "portal_account_login"
  return settings

This will then work:

from django.conf import settings
print(settings.PORTAL_URL)


来源:https://stackoverflow.com/questions/32946157/change-djangos-settings-from-an-external-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!