Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django settings.py os.environ.get("X") not fetching correct values

I am trying to access and fetch (get) value of OS Environment variable into settings.py and while debugging application I get None value for that record. Here are more details:

There are some important/secret keys which can't be shared in code so those are exported in OS environment variables. Whenever I do echo $KEY_VAL from linux terminal or python shell (manage.py shell) it prints the correct value of my environment variable.

But while debugging application, it shows that value is None. I am using ipdb debugger and printing value with following command gives None as result:

p settings.KEY_VAL

In settings.py these are the sentences to get os env variable:

import os; KEY_VAL = os.environ.get("KEY_VAL")

I am using ZSH in my ubuntu system. Here is my ~/.zshrc file:

#
# Executes commands at the start of an interactive session.
#
# Authors:
#   Sorin Ionescu <[email protected]>
#

# Source Prezto.
if [[ -s "${ZDOTDIR:-$HOME}/.zprezto/init.zsh" ]]; then
  source "${ZDOTDIR:-$HOME}/.zprezto/init.zsh"
fi

export KEY_VAL='SOME_JUNK_VAL'


fortune | cowsay | lolcat

# Customize to your needs...

Note: I have changed variable name and value.

But if you can help in anyway I appreciate it.

like image 660
jimish Avatar asked Jun 23 '15 11:06

jimish


1 Answers

Your problem is certainly not with your python code. This works flawlessly in many of our django apps.

My guess is you're not starting the django server from a zsh at all and thus the .zshrc isn't loaded. This is certainly the case for standard nginx/gunicorn setups, where gunicorn is run as a daemon and never through the interactive command line. Also, might be that you're not using the same user for this.

You can verify this by adding the following code somewhere in your django app:

import os
print os.environ

BTW, you might also reconsider injecting your environment variables through the .zshrc. For simple setups, we usually keep them in a .env file and use https://github.com/jpadilla/django-dotenv for reading them at django startup time. Security-wise, this amounts to the same as with your setup, but it isn't bound to a login user.

like image 57
Nuschk Avatar answered Oct 27 '22 00:10

Nuschk