简体   繁体   English

环境变量的 SECRET_KEY 错误

[英]SECRET_KEY errors with environment variables

I am working through the TaskBuster Django tutorial whose goal is to help in the process of setting up a good development setup for a project.我正在完成TaskBuster Django教程,其目标是帮助为项目设置良好的开发设置。

When I run the command echo $SECRET_KEY当我运行命令 echo $SECRET_KEY

In either my "Dev" environment or my "Test" environment I get the same output so I believe that my $ENVIROMENTS/bin/postactivate and predeativate variables are set up correctly.在我的“开发”环境或“测试”环境中,我得到相同的输出,所以我相信我的 $ENVIROMENTS/bin/postactivate 和 predeativate 变量设置正确。

my base.py folder contains我的 base.py 文件夹包含

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# Get SECRET_KEY from the virtual environment
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)

SECRET_KEY = get_env_variable('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'bapsite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'bapsite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

However, when I try to run the tests I get this output.但是,当我尝试运行测试时,我得到了这个输出。

Traceback (most recent call last):
  File "/home/devin/DjangoProjects/bap_project/bapsite/settings/base.py", line 28, in get_env_variable
    return os.environ[var_name]
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/os.py", line 725, in __getitem__
    raise KeyError(key) from None
KeyError: 'SECRET_KEY'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
    super(Command, self).run_from_argv(argv)
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/base.py", line 378, in run_from_argv
    parser = self.create_parser(argv[0], argv[1])
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/base.py", line 351, in create_parser
    self.add_arguments(parser)
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/commands/test.py", line 52, in add_arguments
    test_runner_class = get_runner(settings, self.test_runner)
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/test/utils.py", line 144, in get_runner
    test_runner_class = settings.TEST_RUNNER
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/conf/__init__.py", line 48, in __getattr__
    self._setup(name)
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/conf/__init__.py", line 44, in _setup
    self._wrapped = Settings(settings_module)
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/conf/__init__.py", line 92, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/devin/DjangoProjects/bap_project/bapsite/settings/testing.py", line 2, in <module>
    from .base import *
  File "/home/devin/DjangoProjects/bap_project/bapsite/settings/base.py", line 33, in <module>
    SECRET_KEY = get_env_variable('SECRET_KEY')
  File "/home/devin/DjangoProjects/bap_project/bapsite/settings/base.py", line 31, in get_env_variable
    raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable

This leads me to believe that there is some issue with the secret key but I"m unclear how to troubleshoot from here.这让我相信密钥存在一些问题,但我不清楚如何从这里进行故障排除。

is the return os.environ[var_name] returning the wrong value?返回 os.environ[var_name] 是否返回了错误的值? How do I see what that is returning so I can point it to what I'd prefer it to return?我如何查看返回的内容,以便我可以将其指向我希望它返回的内容? Am I on the correct path to figuring this out?我是否走在正确的道路上来解决这个问题?

Here is the testing file I am using currently这是我目前使用的测试文件

from selenium import webdriver
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import LiveServerTestCase  


class HomeNewVisitorTest(LiveServerTestCase): 

    def setUp(self):
        self.browser = webdriver.Firefox()
        self.browser.implicitly_wait(3)

    def tearDown(self):
        self.browser.quit()

    def get_full_url(self, namespace):
        return self.live_server_url + reverse(namespace)

    def test_home_title(self):
        self.browser.get(self.get_full_url("home"))
        self.assertIn("TaskBuster", self.browser.title)

    def test_h1_css(self):
        self.browser.get(self.get_full_url("home"))
        h1 = self.browser.find_element_by_tag_name("h1")
        self.assertEqual(h1.value_of_css_property("color"), 
                         "rgba(200, 50, 255, 1)")

You don't have an environment variable named SECRET_KEY.您没有名为 SECRET_KEY 的环境变量。 You need to set it before you run your program.您需要在运行程序之前设置它。

On Unix在 Unix 上

export SECRET_KEY="password"

On Windows在 Windows 上

set SECRET_KEY="password"

It's worth noting that the variable will disappear when you close the terminal.值得注意的是,当您关闭终端时,该变量将消失。 There are ways around that if you'd like to look for them.如果您想寻找它们,有一些方法可以解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 环境变量 Django:配置不当:SECRET_KEY 设置不能为空 - Environment Variables Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty 使用环境变量隐藏 Django SECRET_KEY 的问题 - Issue with Hiding Django SECRET_KEY Using environment variables 当生成的 SECRET_KEY 以“$”开头时,如何从环境文件中转义 Django 中的 SECRET_KEY? - How to escape SECRET_KEY in Django from environment file when generated SECRET_KEY begins with '$'? windows 中的设置命令不适用于 django SECRET_KEY | django.core.exceptions.ImproperlyConfigured:设置 SECRET_KEY 环境变量 - set command in windows not working for django SECRET_KEY | django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable VPS 上的 Django SECRET_KEY - Django SECRET_KEY on VPS Django设置SECRET_KEY - Django settings SECRET_KEY 部署Django SECRET_KEY - Deploy Django SECRET_KEY 如何在 Django 中保密 SECRET_KEY? - How to keep a SECRET_KEY secret in Django? 将 Django 部署到 PythonAnywhere 并且无法使用环境变量中的 SECRET_KEY 尽管已设置 - Deploying Django to PythonAnywhere and cannot use SECRET_KEY from environment vars despite it being set 我尝试将可复制的secret_key环境添加到bin / activate的底部,但是它不起作用 - I tried adding secret_key environment cariable to my bottom of bin/activate but it didn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM