我正在尝试运行Django(1.10),但收到错误:
(.venv)$ ./manage.py runserver 0.0.0.0:8000
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
...
File "/home/myapp/myapp/myapp/myapp/settings/local.py", line 5, in <module>
from .base import *
File "/home/myapp/myapp/myapp/myapp/settings/base.py", line 64, in <module>
'NAME': utils.get_env_setting('RETR_DB_NAME'),
File "/home/myapp/myapp/myapp/common/utils.py", line 13, in get_env_setting
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the RETR_DB_NAME env variable
但环境变量已设置:
(.venv) $ echo $RETR_DB_NAME
myname
有问题的代码如下:
def get_env_setting(setting):
""" Get the environment setting or return exception """
try:
return environ[setting]
except KeyError:
error_msg = "Set the %s env variable" % setting
raise ImproperlyConfigured(error_msg)
...
'NAME': utils.get_env_setting('RETR_DB_NAME'),
为什么我能看到环境变量,但Django不能?
答案 0 :(得分:2)
你忘了export
它的可能性。您可以通过以下方式检查问题是否存在:
export -p | fgrep RETR_DB_NAME
如果您忘记export
,则不会输出任何内容,export
可以用来导出它(无论是否已导出,它都不是{{{}}的错误1}}两次):
export
答案 1 :(得分:0)
我个人建议使用os.getenv
来获取变量,这样可以返回默认值。
无论如何,请确保使用export RETR_DB_NAME='db_name'
而不是RETR_DB_NAME='db_name'