由于Pycharm不是从终端启动的,因此不会加载你的环境。简而言之,任何GUI程序都不会继承SHELL变量。
但是,有几个基本解决方案。正如@ user3228589发布的那样,你可以在PyCharm中将其设置为变量。这有几个优点和缺点。我个人不喜欢这种方法,因为它不是一种
single source。为了解决这个问题,我在
settings.py文件顶部使用了一个小函数,该函数在本地
.env文件中查找变量。我把所有的“私人”东西都放在那里。我也可以在我的virtualenv中引用它。
这是它的样子。
-settings.py
def get_env_variable(var_name, default=False): """ Get the environment variable or return exception :param var_name: Environment Variable to lookup """ try: return os.environ[var_name] except KeyError: import StringIO import ConfigParser env_file = os.environ.get('PROJECT_ENV_FILE', SITE_ROOT + "/.env") try: config = StringIO.StringIO() config.write("[DATA]n") config.write(open(env_file).read()) config.seek(0, os.SEEK_SET) cp = ConfigParser.ConfigParser() cp.readfp(config) value = dict(cp.items('DATA'))[var_name.lower()] if value.startswith('"') and value.endswith('"'): value = value[1:-1] elif value.startswith("'") and value.endswith("'"): value = value[1:-1] os.environ.setdefault(var_name, value) return value except (KeyError, IOError): if default is not False: return default from django.core.exceptions import ImproperlyConfigured error_msg = "Either set the env variable '{var}' or place it in your " "{env_file} file as '{var} = VALUE'" raise ImproperlyConfigured(error_msg.format(var=var_name, env_file=env_file))# Make this unique, and don't share it with anybody.SECRET_KEY = get_env_variable('SECRET_KEY')然后,env文件如下所示:
#!/bin/sh## This should normally be placed in the ${SITE_ROOT}/.env## DEPLOYMENT DO NOT MODIFY THESE..SECRET_KEY='XXXSECRETKEY'最后,你的virtualenv / bin / postactivate可以获取此文件。如果愿意,可以进一步进行操作并按此处所述导出变量,但是由于设置文件直接调用.env,因此实际上没有必要。



