5

I set up the django setting.py like this:

import os
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name):
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = "Set the %s environment variable" % var_name
        raise ImproperlyConfigured(error_msg)

The environment variables were configed correctly. When working with the django built in web server, everything was ok. But working with apache and wsgi, it raised an KeyError.

According to Cannot get environment variables in Django settings file, the problem is solved. But why cannot apache get the system environment variables?

UPDATED: The environment variables were set in .bashrc.

Community
  • 1
  • 1
Desmond Chen
  • 492
  • 5
  • 17
  • How are you setting those variables? Don't forget Apache will run as its own user. – Daniel Roseman May 28 '13 at 13:08
  • By "configured correctly", you mean you use the `SetEnv` directive to set them in your Apache config? IIRC, Apache clears the environment, so you need to have directives in place to expose the environment variables you need. – John Szakmeister May 28 '13 at 13:09

2 Answers2

7

You say "The environment variables were set in .bashrc." Presumably you mean your .bashrc. Which is pointless, because Apache is not running as you, it is running as the Apache user.

As explained in the blog post referenced in the very question you link to, you need to set the environment variables in the Apache configuration file itself via the SetEnv directive.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 6
    Except that SetEnv directive alone does not result in process wide environment variables being set for WSGI applications running under mod_wsgi. It only worked because they were using a WSGI wrapper to read them from the WSGI environ and force setting them on every request. Doing this is actually bad practice and ill advised. It is better to simply set them at the start of the WSGI script file so they are set only once when the WSGI script file is first loaded. – Graham Dumpleton May 29 '13 at 04:09
  • 1
    How to set them at the start of the WSGI script file, Graham? – Desmond Chen Jun 01 '13 at 15:26
  • @GrahamDumpleton, curious about this too? How to come about this if we don't maintain multiple wsgi.py files for various environments? THanks. – tejinderss Sep 23 '13 at 19:10
0

whatever environments you are setting in the settings.py will be applied for that instance's environment variables only, they are not changing the system env variables which will be called apache.

abhishekgarg
  • 1,480
  • 9
  • 14