Search code examples
pythondjangovirtualenvvirtualenvwrapper

get virtualenv variables in settings file with wsgi


I've Django application using enviroment variables (security reasons) in my settings.py file:

SECRET_KEY = os.environ['SECRET_KEY']

SECRET_KEY variable is set in my <virtualenv_path>/bin/postactivate:

export SECRET_KEY='trololo'

I've had deployed application with apache, so I've used wsgi.py file activating virtualenv:

activate_env=os.path.expanduser(envP + "/bin/activate_this.py")
execfile(activate_env, dict(__file__=activate_env))

Unfortuanately Apache crashes with following error:

KeyError: 'SECRET_KEY'

What's wrong with my configuration?


Solution

  • The postactivate file is a hook called when you use the workon command in bash. In your case, you call the python script activate_this.py.

    I manage my settings the same way but I have a postactivate_this.py file in order to set my environment variables as in my postactivate file :

    from os import environ
    
    environ["DJANGO_SECRET_KEY"] = "..."
    # etc.
    

    Then in your wsgi.py file you can write :

    activate_env = os.path.expanduser(envP + '/bin/activate_this.py')
    postactivate_env = os.path.expanduser(envP + '/bin/postactivate_this.py')
    
    execfile(activate_env, dict(__file__=activate_env))
    execfile(postactivate_env, dict(__file__=postactivate_env))
    

    You don't need a separate settings file.