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.
答案 0 :(得分:3)
很可能你有一个env变量SECRET_KEY
设置为空字符串。检查是否是这种情况:
$ env | grep SECRET_KEY
SECRET_KEY=
如果这是你得到的,那么你可能试图通过发出
来清除env var$ export SECRET_KEY=
这不会删除变量,而是将其值设置为空值。要删除变量,请发出
$ unset SECRET_KEY
再次发出env | grep SECRET_KEY
验证是否删除了变量,这次输出应为空。
答案 1 :(得分:1)
from django.conf import settings
您不应该在设置中导入设置。删除导入,然后使用SECRET_KEY
代替settings.SECRET_KEY
答案 2 :(得分:0)
万一其他人到此为止。对我来说,问题是我正在通过PyCharm运行本地运行服务器。
PyCharm通过使用manage.py文件将设置模块设置为环境变量。要解决此问题,我必须打开运行配置并编辑环境变量。
如果您在设置文件方面遇到麻烦,只需检查一下IDE是否有任何偷偷摸摸的事情。