Python Pycharm:为运行 manage.py 任务设置环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21538859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:06:29  来源:igfitidea点击:

Pycharm: set environment variable for run manage.py Task

pythondjangopycharm

提问by Cole

I have moved my SECRET_KEYvalue 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.

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

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

当我运行 Django 控制台时,SECRET_KEY它应该丢失。所以在首选项中,我转到 Console>Django Console 并加载SECRET_KEY和适当的值。我回到 Django 控制台,SECRET_KEY就在那里。

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_KEYinto Django server and Django Tests, and into the project server. Restart Pycharm, confirm keys.

正如预期的那样,我还不能运行 manage.py 任务,因为它还没有找到SECRET_KEY. 所以我进入 Run>Edit Configurations 以添加SECRET_KEY到 Django 服务器和 Django 测试,以及项目服务器。重启Pycharm,确认键。

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

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

Where do I put this key?

我把这把钥匙放在哪里?

采纳答案by rh0dium

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

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

However, there are several basic solutions to this problem. As @user3228589posted, 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 .envfile. I put all of my "private" stuff in there. I also can reference this in my virtualenv.

然而,这个问题有几个基本的解决方案。正如@user3228589发布的那样,您可以将其设置为 PyCharm 中的变量。这有几个优点和缺点。我个人不喜欢这种方法,因为它不是single source. 为了解决这个问题,我在我的 settings.py 文件顶部使用了一个小函数,它在本地.env文件中查找变量。我把我所有的“私人”东西都放在那里。我也可以在我的 virtualenv 中引用它。

Here is what it looks like.

这是它的样子。

-- settings.py

-- 设置.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')

Then the env file looks like this:

然后 env 文件如下所示:

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

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

最后你的 virtualenv/bin/postactivate 可以获取这个文件。你可以去进一步和导出为描述的变量在这里,如果你愿意,但由于设置文件直接调用.ENV,确实没有必要。

回答by ammonium

Same here, for some reason PyCharm cant see exported env vars. For now i set SECRET_KEY in PyCharm Run/Debug Configurations -> "Environment variables"

同样在这里,出于某种原因,PyCharm 无法看到导出的环境变量。现在我在 PyCharm 运行/调试配置中设置 SECRET_KEY ->“环境变量”

回答by nu everest

To set your environment variables in PyCharm do the following:

要在 PyCharm 中设置环境变量,请执行以下操作:

  • Open the 'File' menu
  • Click 'Settings'
  • Click the '+' sign next to 'Console'
  • Click Python Console
  • Click the '...' button next to environment variables
  • Click the '+' to add environment variables
  • 打开“文件”菜单
  • 点击“设置”
  • 单击“控制台”旁边的“+”号
  • 单击 Python 控制台
  • 单击环境变量旁边的“...”按钮
  • 单击“+”添加环境变量

回答by OmriToptix

You can set the manage.py task environment variables via:

您可以通过以下方式设置 manage.py 任务环境变量:

Preferences| Languages&Frameworks| Django| Manage.py tasks

偏好| 语言&框架| 姜戈| Manage.py 任务

Setting the env vars via the run/debug/console configuration won't affect the built in pycharm's manage.py task.

通过运行/调试/控制台配置设置环境变量不会影响内置的 pycharm 的 manage.py 任务。

回答by danfromisrael

based on @rh0dium amazing answer i've made this class:

基于@rh0dium 惊人的答案,我做了这门课:

here's my settings.py:

这是我的 settings.py:

import os


class EnvironmentSettings():
    """Access to environment variables via system os or .env file for development

    """
    def __init__(self, root_folder_path):
        self._root_folder_path = root_folder_path

    def __getitem__(self, key):
        return self._get_env_variable(key)

    def __setitem__(self, key, value):
        raise InvalidOperationException('Environment Settings are read-only')

    def __delitem__(self, key):
        raise InvalidOperationException('Environment Settings are read-only')

    def _get_env_variable(self, 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:
            from io import StringIO
            from configparser import ConfigParser

            env_file = os.environ.get('PROJECT_ENV_FILE', self._root_folder_path + "/.env")
            try:
                config = StringIO()
                config.write("[DATA]\n")
                config.write(open(env_file).read())
                config.seek(0, os.SEEK_SET)
                cp = 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
                error_msg = "Either set the env variable '{var}' or place it in your " \
                            "{env_file} file as '{var} = VALUE'"
                raise ConfigurationError(error_msg.format(var=var_name, env_file=env_file))


class ConfigurationError(Exception):
    pass


class InvalidOperationException(Exception):
    pass

and inside my runserver.py i have this calling code:

在我的 runserver.py 中,我有这个调用代码:

from settings import EnvironmentSettings

root_folder_path = os.path.dirname(os.path.abspath(__file__))
env_settings = EnvironmentSettings(root_folder_path)
config_name = env_settings['APP_SETTINGS']

回答by Antero Ortiz

Another option that's worked for me:

另一个对我有用的选择:

  1. Open a terminal
  2. Activate the virtualenv of the project which will cause the hooks to run and set the environment variables
  3. Launch PyCharm from this command line.
  1. 打开终端
  2. 激活项目的 virtualenv 这将导致钩子运行并设置环境变量
  3. 从此命令行启动 PyCharm。

Pycharm will then have access to the environment variables. Likely because of something having to do with the PyCharm process being a child of the shell.

然后 Pycharm 将可以访问环境变量。可能是因为 PyCharm 进程是 shell 的子进程。

回答by Nitin

The answer by @(nu everest) did not work for me. Whatever you described in the question worked for me. You can set all environment variables in the Run/Debug Configurations dialog. This is w.r.t PyCharm 2016.1 and also as per https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-python.html?origin=old_help

@(nu everest) 的回答对我不起作用。您在问题中描述的任何内容都对我有用。您可以在“运行/调试配置”对话框中设置所有环境变量。这是 PyCharm 2016.1,也根据https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-python.html?origin=old_help

回答by jaywink

I'm trying this setup currently. I have an env.localfile in my project root. My manage.pylooks like this:

我目前正在尝试此设置。我的env.local项目根目录中有一个文件。我的manage.py看起来像这样:

#!/usr/bin/env python
import os
import sys


if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")

    # Load environment variables from env.local, if option --load-env specified.
    # Good for injecting environment into PyCharm run configurations for example and no need to
    # manually load the env values for manage.py commands
    if "--load-env" in sys.argv:
        with open("env.local") as envfile:
            for line in envfile:
                if line.strip():
                    setting = line.strip().split("=", maxsplit=1)
                    os.environ.setdefault(setting[0], setting[1])
        sys.argv.remove("--load-env")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

Then I just pass --load-envin the PyCharm run dialog and all the environment variables will be loaded in for the time of the run.

然后我只需传入--load-envPyCharm 运行对话框,所有环境变量将在运行时加载。

回答by Ben

To paraphrase @antero-ortiz'sanswer, instead of using the default Mac double-click or spotlight search to launch PyCharm, you can launch it directly from the terminal. This will inherit all of your environment variables from your terminal session to the PyCharm app.

套用@antero-ortiz 的回答,您可以直接从终端启动 PyCharm,而不是使用默认的 Mac 双击或聚焦搜索来启动 PyCharm。这会将您的所有环境变量从您的终端会话继承到 PyCharm 应用程序。

Here's how I solve this issue.

这是我解决这个问题的方法。

  1. From your terminal program, run the snippet below.
  2. Validate that things worked by following the instructions to Edit your Run/Debug Configurationsand,
    1. Clicking the ...next to Environment variables
    2. Then clicking Showat the bottom right of the screen that pops up. This will show allof the environment variables inherited by the Debug process.
    3. Find your SECRET_KEYin this list. If it's not there, post a comment on this answer and we can try to figure it out!
  3. You'll likely need to launch PyCharm this way every time you start it.
  1. 在您的终端程序中,运行下面的代码片段。
  2. 按照编辑运行/调试配置的说明验证事情是否有效,并且,
    1. 点击...旁边的Environment variables
    2. 然后点击Show弹出的屏幕右下角的。这将显示调试进程继承的所有环境变量。
    3. SECRET_KEY在此列表中找到您的。如果它不存在,请对此答案发表评论,我们可以尝试找出答案!
  3. 每次启动 PyCharm 时,您可能都需要以这种方式启动它。

Snippet:

片段:

# This file would presumably export SECRET_KEY
source /path/to/env/file
# This is just a shortcut to finding out where you installed PyCharm
# If you used brew cask, it's probably in /opt/homebrew-cask/Caskroom/pycharm
open $(locate PyCharm.app | egrep 'PyCharm.app$')

Side note

边注

Including environment variables in a file that is then source'd is a common pattern for Django development, and the discussion of that best practice is best left out of answers.

将环境变量包含在一个文件中,然后source'd 是 Django 开发的常见模式,最好不要回答有关该最佳实践的讨论。

回答by cvng

In Pycharm manage.pytasks run in an isolated process that do not have access to your environment variables (not the same as Run/Debug).

在 Pycharm 中,manage.py任务在无法访问环境变量的隔离进程中运行(与运行/调试不同)。

The simplest solution is to make your python code aware of environment variables by reading them from your .envfile directly.

最简单的解决方案是通过.env直接从文件中读取环境变量,让您的 Python 代码知道环境变量。

Take a look at: https://github.com/joke2k/django-environ

看一看:https: //github.com/joke2k/django-environ

import environ

env = environ.Env.read_env() # reading .env file

SECRET_KEY = env('SECRET_KEY')

That way you have a single source of configurations, and less settings in the IDE.

这样,您就有了单一的配置来源,并且 IDE 中的设置更少。

Hope that helps,

希望有所帮助,