无法访问Django设置中的os.environ

时间:2015-04-27 19:59:42

标签: python django environment-variables

我在Django App中有这些代码行

import os
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'noodles',
        'USER': 'khophi',
        'PASSWORD': os.environ['DB_PASSWORD'], # I have this part in my system environment. I can verify
        'HOST': 'localhost',
        'PORT': '',
    }
}

如何验证终端中是否存在变量:

import os
os.environ['DB_PASSWORD'] # returns the value stored in there

当我通过Django设置调用相同的值时,我收到此错误:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 303, in execute
    settings.INSTALLED_APPS
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 48, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 44, in _setup
    self._wrapped = Settings(settings_module)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 92, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/noodles/Noodles/settings.py", line 117, in <module>
    'PASSWORD': os.environ['DB_PASSWORD'],
  File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'DB_PASSWORD'

我将值添加到~/.pam_environment。服务器在与~/.pam_environment相同的用户中运行。

为什么我无法访问os.environ值?

编辑:我已经看到环境变量如何暴露给Django设置,但它们适用于apache mod_wsgi。我可以为django-nginx-gunicorn做类似的事吗?

0 个答案:

没有答案