gpt4 book ai didi

Django key 错误

转载 作者:行者123 更新时间:2023-12-02 06:50:20 25 4
gpt4 key购买 nike

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

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

此错误没有意义,因为我设置了 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.

最佳答案

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

$ env | grep SECRET_KEY
SECRET_KEY=

如果这是您得到的结果,那么您可能尝试通过发出来清除环境变量

$ export SECRET_KEY=

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

$ unset SECRET_KEY

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

关于Django key 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com