Cannot use environment variables for settings in Django

后端 未结 2 402
失恋的感觉
失恋的感觉 2021-02-03 10:42

In trying to find a place to store and save settings beyond settings.py and the database, I used an environment.json for environment variables. I import these in settings.py.

2条回答
  •  遇见更好的自我
    2021-02-03 10:52

    I see the question changed slightly, the original answers are still below but this one has a slightly different answer:


    First, make sure you are using the right settings.py (print 'This file is being loaded' should do the trick).

    Second, personally I would advise against using json files for config since it is less dynamic than Python files, but it should work regardless.

    My recommended way of doing something like this:

    1. create a base_settings.py file with your standard settings
    2. create a settings.py which will be your default settings import. This file should have a from base_settings import * at the top to inherit the base settings.
    3. If you want to have a custom settings file, dotcloud_settings.py for example, simply add the from dotcloud_settings import settings (or base_settings) and set the environment variable DJANGO_SETTINGS_MODULE to dotcloud_settings or your_project.dotcloud_settings depending on your setup.

    Do note that you should be very careful with importing Django modules from these settings files. If any module does a from django.conf import settings it will stop parsing your settings after that point.

    As for using json files, roughly the same principle of course:

    • Once again, make sure you don't have anything that imports django.conf.settings here
    • Make all of the variables within your json file global to your settings file:

      import json with open('/home/dotcloud/environment.json') as f: env = json.load(f) # A little hack to make all variables within our env global globals().update(env)


    Regardless though, I'd recommend turning this around and letting the settings file import this module instead.

    Also, Django doesn't listen to environment variables by default (besides the DJANGO_SETTINGS_MODULE so that might be the problem too.

提交回复
热议问题