Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"os.environ" in django settings.py cannot get system environment variables with apache and wsgi

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.

like image 554
Desmond Chen Avatar asked May 28 '13 12:05

Desmond Chen


People also ask

How do I set environment variables in environ?

To set and get environment variables in Python you can just use the os module: import os # Set environment variables os. environ['API_USER'] = 'username' os. environ['API_PASSWORD'] = 'secret' # Get environment variables USER = os.

How do I set an environment variable in Django?

Creating Environment Variables Create a . env file in the same directory where settings.py resides and add the following key-value pair inside the file. We will use django-environ for managing environment variables inside our project. So let's install the package.

What is OS environ in Django?

django-environ is the Python package that allows you to use Twelve-factor methodology to configure your Django application with environment variables.


1 Answers

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.

like image 180
Daniel Roseman Avatar answered Oct 12 '22 12:10

Daniel Roseman