1

I am working on a Django application. I want to put the SECRET_KEY in environment variables. I added this to the .bashrc file:

export SECRET_KEY=sdfsjhsuresfsdf

The i did source .bashrc

I am able to access the environment variable from python shell using:

import os
os.environ['SECRET_KEY']

But, it shows a keyError when I try to access this from settings.py file. What am I doing wrong?

toothie
  • 1,019
  • 4
  • 20
  • 47

1 Answers1

0

Try:

export SECRET_KEY=sdfsjhsuresfsdf

Then re-source. And start a new Python instance. It should then be visible.

Bash doesn't always auto-export its variables.

In general, OS environment variables are a hard place to put configuration information reliably, because of such issues. It's hard to track down why variables are seen or not seen. Reading configuration information out of configuration files (whether .ini, .json, or some other format) is a bit more robust. But, environment variables are very commonly used, so, when in Rome...

Jonathan Eunice
  • 21,653
  • 6
  • 75
  • 77
  • Still the same error. Is there some other way to put keys safely? – toothie Oct 09 '14 at 04:42
  • Drop out of Python, to the bash shell. Run `echo $SECRET_KEY`. That will show you if the shell properly knows about the variable. Is your Django app being run from a shell that has the SECRET_KEY properly set? – Jonathan Eunice Oct 09 '14 at 05:02
  • And then you run your Django app from that shell, and the Django app doesn't pick up the proper environment variable setting? – Jonathan Eunice Oct 09 '14 at 05:16
  • Or are you running the Django app from a web server setup (like under Apache)? If so, it's running from a different shell that will never source your local `.bashrc`. See also [this](http://stackoverflow.com/questions/16395491/cannot-get-environment-variables-in-django-settings-file). – Jonathan Eunice Oct 09 '14 at 05:21
  • Yes I am running from a web server setup (Gunicorn) – toothie Oct 09 '14 at 06:15
  • 1
    @Monique, that's why. .bashrc is user specific and it's another user running gunicorn. The problem is that that user won't load his .bashrc either since it doesn't need to load bash to run the web server. You should look into another solution than environment variables. – olofom Oct 09 '14 at 09:34
  • Ok, thanks. I am keeping them in a separate file now. – toothie Oct 09 '14 at 10:46