本文介绍了在Django设置文件中无法获取环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Django设置中读取一些环境变量,我在/home/user/.bashrc中定义了一些环境变量(后者在/etc/bash.bashrc中),但是我所有的都是一个KeyError异常。我知道我的环境变量已设置,因为我可以在终端中打印(echo $ VAR_NAME)。这应该是微不足道的。



这是我使用的代码。

  from django.core.exceptions import不正确配置

msg =设置%s环境变量


def get_env_variable(var_name):
尝试:
返回os.environ [var_name]
除了KeyError:
error_msg = msg%var_name
raise不正确的配置(error_msg)

OS_DB_USER = get_env_variable ('MY_USER')
OS_DB_PASS = get_env_variable('MY_PASS')
OS_DB_DB = get_env_variable('MY_DB')
OS_GAME_LOGS = get_env_variable('DIR_LOGS')

我找不到缺少的东西。有什么建议吗?



谢谢



编辑:使用mod_wsgi在Apache上运行

解决方案

我使用这个解决方案解决了我的问题:




I'm trying to read some environment variables in Django settings, which i have defined in /home/user/.bashrc (and latter in /etc/bash.bashrc ) , but all i get is a KeyError exception. I know my environment variables are set, because i can print them in the terminal (echo $VAR_NAME). This should be trivial.

This is the code i'm using.

from django.core.exceptions import ImproperlyConfigured

msg = "Set the %s environment variable"


def get_env_variable(var_name):
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = msg % var_name
        raise ImproperlyConfigured(error_msg)

OS_DB_USER = get_env_variable('MY_USER')
OS_DB_PASS = get_env_variable('MY_PASS')
OS_DB_DB = get_env_variable('MY_DB')
OS_GAME_LOGS = get_env_variable('DIR_LOGS')

I just can't find what's missing. Any suggestions out there?

Thanks

EDIT: Running on Apache with mod_wsgi.

解决方案

I've manage to solve my problem by using this solution:

http://drumcoder.co.uk/blog/2010/nov/12/apache-environment-variables-and-mod_wsgi/

这篇关于在Django设置文件中无法获取环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 05:31