Django SECRET KEY 错误

Posted

技术标签:

【中文标题】Django SECRET KEY 错误【英文标题】:Django SECRET KEY error 【发布时间】:2018-09-03 22:39:52 【问题描述】:

我正在构建一个小的 Django REST API。我已经为本地和生产配置了一个单独的设置模块,但是我遇到了一个恼人的错误:

django.core.exceptions.ImproperlyConfigured:SECRET_KEY 设置 不能为空。

这个错误没有意义,因为我设置了 SECRET_KEY 变量。这是我的 base.py(这是我的 API 的基本设置)和 local.py。另外,这是我的 wsgi.py 和 manage.py。

base.py

"""
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import datetime
import os

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

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

SECRET_KEY = os.environ.get('SECRET_KEY', 'mmglfamx3n927*93$ks#r)h%*a(@))vb7*=2q$&z(=6@q&*ghj')

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'api',
    'drf_yasg',
]

REST_FRAMEWORK = 
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    )


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'petevip.urls'

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR, 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 = 'petevip.wsgi.application'

# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    ,
]

# Internationalization
# https://docs.djangoproject.com/en/2.0/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/2.0/howto/static-files/

STATIC_URL = '/static/'

AUTH_USER_MODEL = 'api.Shop'

JWT_AUTH = 
    'JWT_ENCODE_HANDLER':
        'rest_framework_jwt.utils.jwt_encode_handler',

    'JWT_DECODE_HANDLER':
        'rest_framework_jwt.utils.jwt_decode_handler',

    'JWT_PAYLOAD_HANDLER':
        'rest_framework_jwt.utils.jwt_payload_handler',

    'JWT_PAYLOAD_GET_USER_ID_HANDLER':
        'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',

    'JWT_RESPONSE_PAYLOAD_HANDLER':
        'api.utils.jwt_payload.jwt_response_payload_handler',

    'JWT_SECRET_KEY': settings.SECRET_KEY,
    'JWT_GET_USER_SECRET_KEY': None,
    'JWT_PUBLIC_KEY': None,
    'JWT_PRIVATE_KEY': None,
    'JWT_ALGORITHM': 'HS256',
    'JWT_VERIFY': True,
    'JWT_VERIFY_EXPIRATION': True,
    'JWT_LEEWAY': 0,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=6000),
    'JWT_AUDIENCE': None,
    'JWT_ISSUER': None,

    'JWT_ALLOW_REFRESH': False,
    'JWT_REFRESH_EXPIRATION_DELTA': None,

    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    'JWT_AUTH_COOKIE': None,



SWAGGER_SETTINGS = 
    'USE_SESSION_AUTH': False,

local.py

from petevip.settings.base import *

DEBUG = True
ALLOWED_HOSTS = ['']

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'petevip_db',
        'USER': 'postgres',
        'PASSWORD': 'DvCglg&282300*kwzsk^x14c3qB4%F2eCMn8',
        'HOST': '172.17.0.2',
        'PORT': '5432',
    

wsgi.py

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefaul("DJANGO_SETTINGS_MODULE", "petevip.settings.local")

application = get_wsgi_application()

ma​​nage.py

import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "petevip.settings.local")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

这也是我的文件夹结构:

petevip-api/
 |-- petevip/
 |    |-- __init__.py
 |    |-- settings/
 |    |    |-- __init__.py
 |    |    |-- base.py
 |    |    |-- local.py
 |    |    +-- production.py
 |    |-- urls.py
 |    +-- wsgi.py
 +-- manage.py

如果有人可以帮助我解决这个问题,我将非常高兴!提前致谢!

编辑:

错误完整跟踪:

Traceback (most recent call last):
  File "./manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv
    super().run_from_argv(argv)
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/core/management/base.py", line 280, in run_from_argv
    parser = self.create_parser(argv[0], argv[1])
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/core/management/base.py", line 254, in create_parser
    self.add_arguments(parser)
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/core/management/commands/test.py", line 47, in add_arguments
    test_runner_class = get_runner(settings, self.test_runner)
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/test/utils.py", line 304, in get_runner
    test_runner_class = settings.TEST_RUNNER
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup
    self._wrapped = Settings(settings_module)
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/albertdiaz/development/petevip-project/petevip-api/petevip/settings/local.py", line 1, in <module>
    from petevip.settings.base import *
  File "/home/albertdiaz/development/petevip-project/petevip-api/petevip/settings/base.py", line 127, in <module>
    'JWT_SECRET_KEY': settings.SECRET_KEY,
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup
    self._wrapped = Settings(settings_module)
  File "/home/albertdiaz/development/petevip-project/petevip-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 125, in __init__
    raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.

【问题讨论】:

设置ALLOWED_HOSTS = [''] 可能会导致问题,但这可能不是这里的问题。默认为ALLOWED_HOSTS = [] 这是在本地发生的吗?当 django 不知道要指向哪些设置文件时,我会看到此错误,因此请使用 python manage.py runserver --settings=petevip.settings.local 对其进行测试以查看它是否运行。 这是你base.py的实际内容吗?第一行是一个 URL,其余的是一个巨大的多行字符串而不是代码。 @kichik nop,我现在已经编辑过了,我的错。 您应该在将数据库密码和密钥发布到此处后更改它们。黑客可以利用这些来破坏您的网站。 【参考方案1】:

很可能你有一个环境变量SECRET_KEY 设置为一个空字符串。检查是否是这种情况:

$ env | grep SECRET_KEY
SECRET_KEY=

如果这是你得到的,那么你可能试图通过发出来清除 env var

$ export SECRET_KEY=

这不会删除变量,而是将其值设置为空值。要删除变量,请发出

$ unset SECRET_KEY

通过再次发出env | grep SECRET_KEY 来验证变量是否已删除,这次输出应该为空。

【讨论】:

谢谢,我会尝试让您知道这是不是错误。 我试过了,变量 SECRET_KEY 肯定是空的。但我有同样的错误 如何检查windows中是否设置了SECRET_KEY环境变量? @AjitGoel 查看How can I display the contents of an environment variable from the command prompt in Windows 7? @hoefling,是否在计算机中设置了环境变量,与在 Django 中设置环境变量(SECRET_KEY)一样吗?我在问,因为我在运行“env | grep SECRET_KEY SECRET_KEY=" 命令时出错【参考方案2】:

以防其他人在这里结束。对我来说,问题是我通过 PyCharm 运行本地运行服务器。

PyCharm 将设置模块设置为环境变量,而不是使用 manage.py 文件。为了解决这个问题,我必须打开运行配置并编辑环境变量。

如果您在设置文件方面遇到问题,请检查您的 IDE 没有做任何偷偷摸摸的事情。

【讨论】:

【参考方案3】:
from django.conf import settings

您不应该在设置中导入设置。删除导入,并使用SECRET_KEY 而不是settings.SECRET_KEY

【讨论】:

以上是关于Django SECRET KEY 错误的主要内容,如果未能解决你的问题,请参考以下文章

gpg: no default secret key: 私钥不可用

更改 Django 的 SECRET_KEY 的效果

django.core.exceptions.ImproperlyConfigured:设置 SECRET_KEY 环境变量

Django:配置不当:SECRET_KEY 设置不能为空

Django--bug--ImproperlyConfigured: The SECRET_KEY setting must not be empty.

在 miniconda 环境中隐藏 django secret_key 时出错