Django SECRET KEY error

放肆的年华 提交于 2020-01-15 07:25:27

问题


I'm building a little Django REST API. I've configured a separate settings module for local and production but I'm having an annoying error which is:

django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.

This error doesn't make sense because I have the SECRET_KEY variable set. Here are my base.py (which is my base settings for the API) and the local.py. Also, here are my wsgi.py and 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()

manage.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)

Also this is my folder structure:

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

If anyone can help me with this problem I will be very glad! Thanks in advance!

EDIT:

Error full trace:

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.

回答1:


Most probably you have an env variable SECRET_KEY set to an empty string. Check if this is the case:

$ env | grep SECRET_KEY
SECRET_KEY=

If this is what you get, then you have probably tried to clear the env var by issuing

$ export SECRET_KEY=

This will not remove the variable, but instead set its value to an empty value. To remove the variable, issue

$ unset SECRET_KEY

Verify the variable is removed by issuing env | grep SECRET_KEY again, this time the output should be empty.




回答2:


from django.conf import settings

You shouldn’t be importing settings inside settings. Remove the import, and use SECRET_KEY instead of settings.SECRET_KEY




回答3:


In case anyone else ends up here. For me the issue was that I was running the local run server through PyCharm.

PyCharm sets the setting module as an environment variable over riding your manage.py file. To fix this I had to open the run configurations and edit the Environment variables.

Just check that your IDE isn't doing anything sneaky if you're having trouble with the settings file.



来源:https://stackoverflow.com/questions/49480389/django-secret-key-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!