Pycharm:设置运行manage.py Task的环境变量 [英] Pycharm: set environment variable for run manage.py Task

查看:2532
本文介绍了Pycharm:设置运行manage.py Task的环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将我的 SECRET_KEY 值移出我的设置文件,并在加载了我的virtualenv时设置。我可以确认该值存在于 python manage.py shell

I have moved my SECRET_KEY value out of my settings file, and it gets set when I load my virtualenv. I can confirm the value is present from python manage.py shell.

当我运行Django控制台时, code> SECRET_KEY 缺少,因为它应该。所以在首选项中,我去控制台> Django控制台,加载 SECRET_KEY 和适当的值。我回到Django控制台, SECRET_KEY 在那里。

When I run the Django Console, SECRET_KEY is missing, as it should. So in preferences, I go to Console>Django Console and load SECRET_KEY and the appropriate value. I go back into the Django Console, and SECRET_KEY is there.

如预期,我还没有运行一个管理.py任务,因为它还没有找到 SECRET_KEY 。所以我进入运行>编辑配置,将 SECRET_KEY 添加到Django服务器和Django测试中,并进入项目服务器。重新启动Pycharm,确认密钥。

As expected, I cannot yet run a manage.py Task because it has yet to find the SECRET_KEY. So I go into Run>Edit Configurations to add SECRET_KEY into Django server and Django Tests, and into the project server. Restart Pycharm, confirm keys.

当我运行一个manage.py任务,例如 runserver ,我仍然会得到 KeyError:'SECRET_KEY'。

When I run a manage.py Task, such as runserver, I still get KeyError: 'SECRET_KEY'.

我在哪里放这个密钥?

推荐答案

由于Pycharm不是从终端启动,您的环境将无法加载。简而言之,任何GUI程序都不会继承SHELL变量。请参阅(假设为Mac)。

Because Pycharm is not launching from a terminal your environment will not loaded. In short any GUI program will not inherit the SHELL variables. See this for reasons (assuming a Mac).

然而,这个问题有几个基本的解决方案。由于 @ user3228589 发布,您可以将其设置为PyCharm中的变量。这有几个利弊。我个人不喜欢这种方法,因为它不是一个单个源。为了解决这个问题,我使用一个位于我的settings.py文件顶部的小函数,该文件在本地的 .env 文件中查找变量。我把我所有的私人东西放在那里。我也可以在我的virtualenv中参考这个。

However there are several basic solutions to this problem. As @user3228589 posted you can set this up as a variable within PyCharm. This has several pros and cons. I personally don't like this approach because it's not a single source. To fix this I use a small function at the top of my settings.py file which looks up the variable inside a local .env file. I put all of my "private" stuff in there. I also can reference this in my virtualenv.

这是它的外观。

- 设置。 py

-- 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文件看起来像这样..

Then the env file looks like this..

#!/bin/sh
#
# This should normally be placed in the ${SITE_ROOT}/.env
#
# DEPLOYMENT DO NOT MODIFY THESE..
SECRET_KEY='XXXSECRETKEY'

最后,您的virtualenv / bin / postactivate可以源文件。您可以进一步输出变量,如这里,如果你愿意,但是由于设置文件直接调用.env,那真的不需要。

And finally your virtualenv/bin/postactivate can source this file. You could go further and export the variables as described here if you'd like but since settings file directly call the .env there isn't really a need.

这篇关于Pycharm:设置运行manage.py Task的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆