Django / Python - 无法使用os.environ.get获取环境变量

时间:2021-11-23 10:31:56

In my Django project, I need to have access to DJANGO_DEVELOPMENT environment variable which tells whether is it a development server or production (droplet on DigitalOcean).

在我的Django项目中,我需要访问DJANGO_DEVELOPMENT环境变量,它告诉它是开发服务器还是生产(DigitalOcean上的Droplet)。

I want to set DJANGO_DEVELOPMENT to 1 on this droplet but it doesn't work.

我想在这个Droplet上将DJANGO_DEVELOPMENT设置为1,但它不起作用。

I've added to /etc/environment this line:

我在/ etc / environment这行添加了:

DJANGO_DEVELOPMENT="1"

And restarted whole Droplet.

并重新启动整个Droplet。

Then, I'm trying to log this variable inside settings.py:

然后,我正在尝试在settings.py中记录此变量:

if os.environ.get('DJANGO_DEVELOPMENT') == '1':
    logger.info('DJANGO_DEVELOPMENT=="1"')
    from dev_settings import *
else:
    logger.info('no DJANGO_DEVELOPMENT VAR')
    logger.info(os.environ.get('DJANGO_DEVELOPMENT'))
    logger.info(os.environ.items())

Which logs this:

记录这个:

2018-03-24 13:09:43,007 - MyProject.settings - INFO - no DJANGO_DEVELOPMENT VAR
2018-03-24 13:09:43,007 - MyProject.settings - INFO - None
2018-03-24 13:09:43,014 - MyProject.settings - INFO - [('LANG', 'en_US.UTF-8'), ('SUPERVISOR_SERVER_URL', 'unix:///var/run/supervisor.sock'), ('SUPERVISOR_ENABLED', '1'), ('SUPERVISOR_PROCESS_NAME', 'daphne'), ('DJANGO_SETTINGS_MODULE', 'MyProject.settings'), ('SUPERVISOR_GROUP_NAME', 'daphne'), ('PATH', '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'), ('LC_ALL', 'en_US.UTF-8')]

But when I ssh to the droplet and check variable manually, it seems to be set:

但是当我ssh到Droplet并手动检查变量时,似乎设置了:

root@MyProject-v1:~# echo $DJANGO_DEVELOPMENT 
1
root@MyProject-v1:~# su - futilestudio 
futilestudio@MyProject-v1:~$ echo $DJANGO_DEVELOPMENT 
1
futilestudio@MyProject-v1:~$ 

Don't know where is the problem, isn't it a bug?

不知道问题在哪里,是不是一个bug?

2 个解决方案

#1


0  

Try to write also

也尝试写

export DJANGO_DEVELOPMENT="1"

in /etc/environment or .bash_profile

在/ etc / environment或.bash_profile中

#2


0  

For working Django receives DJANGO_SETTINGS_MODULE enviroment variable. Pass your variable at the same way.

对于工作Django收到DJANGO_SETTINGS_MODULE环境变量。以相同的方式传递您的变量。

P.S. Configure development/productions states by passing enviroment variable is not good way, use different settings modules for different states.

附:通过传递环境变量来配置开发/生产状态并不是好办法,对不同的状态使用不同的设置模块。

#1


0  

Try to write also

也尝试写

export DJANGO_DEVELOPMENT="1"

in /etc/environment or .bash_profile

在/ etc / environment或.bash_profile中

#2


0  

For working Django receives DJANGO_SETTINGS_MODULE enviroment variable. Pass your variable at the same way.

对于工作Django收到DJANGO_SETTINGS_MODULE环境变量。以相同的方式传递您的变量。

P.S. Configure development/productions states by passing enviroment variable is not good way, use different settings modules for different states.

附:通过传递环境变量来配置开发/生产状态并不是好办法,对不同的状态使用不同的设置模块。