Wednesday, March 26, 2014

Setting environmental variables in virtualenv

I am taking a stab at my first Django project.  As with all web apps, I am concerned with security, so I decided to set my SECRET_KEY as an environmental variable.  Fortunately, this is not too hard to do if you have virtualenvwrapper.  Here is a pretty good Stack Overflow thread about that:

http://stackoverflow.com/questions/9554087/setting-an-environment-variable-in-virtualenv

After reading the thread multiple times, I did the following. First I located the bin directory of the virtual environment I was using ($HOME/.virtualenvs/tapeworm_django/bin).  Inside I found the postactivate hook, which is an executable file and modified it like so:

#!/bin/bash
# This hook is run after this virtualenv is activated.


export SECRET_KEY=myKey

Then I found the predactivate hook and added the following:

#!/bin/bash
# This hook is run before this virtualenv is deactivated.

unset SECRET_KEY

Now will the SECRET_KEY variable will be set and unset when I decided to work on the tapeworm_django virtual environment:

christohersmbp2:tapeworm_django christopherspears$ workon tapeworm_django
(tapeworm_django)christohersmbp2:tapeworm_django christopherspears$ echo $SECRET_KEY
myKey
(tapeworm_django)christohersmbp2:tapeworm_django christopherspears$ deactivate
christohersmbp2:tapeworm_django christopherspears$ echo $SECRET_KEY

christohersmbp2:tapeworm_django christopherspears$

Now in settings.py file of the project configuration directory, I set secret key like so:

SECRET_KEY =  os.environ['SECRET_KEY']

No comments:

Post a Comment