如何解决在 Django 中执行 manage.py runserver 命令时的错误原因?
Posted
技术标签:
【中文标题】如何解决在 Django 中执行 manage.py runserver 命令时的错误原因?【英文标题】:How to fix the error cause when execute manage.py runserver command in Django? 【发布时间】:2020-01-04 23:21:10 【问题描述】:我最近加入了使用 Django 框架完成的正在进行的项目,我是这个框架的新手。这段代码不是我的。当我运行 python manage.py runserver 命令时,我收到以下错误。
我已经完成了自述文件中要求的所有配置。
这是local.py文件
try:
from .base import *
except ImportError:
pass
from configparser import RawConfigParser
config = RawConfigParser()
config.read('/etc/django_settings/hopster_settings.ini')
SECRET_KEY = config.get('secrets', 'SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS += [
'rest_framework_swagger', # to enable swagger documentation for rest api
'django_extensions', # for print db schemas
]
DATABASES =
'default':
'ENGINE': config.get('database', 'DATABASE_ENGINE'),
'NAME': config.get('database', 'DATABASE_NAME'),
'USER': config.get('database', 'DATABASE_USER'),
'PASSWORD': config.get('database', 'DATABASE_PASSWORD'),
'HOST': config.get('database', 'DATABASE_HOST'),
'PORT': config.get('database', 'DATABASE_PORT'),
SITE_ID = 1
STATIC_URL = '/static/'
STATIC_NAME = 'hopster_static_cdn'
MEDIA_NAME = 'hopster_media_cdn'
STATICFILES_DIRS = [
os.path.join(os.path.dirname(BASE_DIR), "static"),
# '/var/www/static/',
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), STATIC_NAME)
# STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'images', 'static')
# STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "english_vlog_static_cdn")
# media files on local server
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), MEDIA_NAME)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
REST_FRAMEWORK =
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer', # convert rest output into json format by ignoring browsable API
'rest_framework.renderers.BrowsableAPIRenderer', # to get the browsable API in web
),
# 'DEFAULT_PARSER_CLASSES': (
# 'rest_framework.parsers.JSONParser',
# )
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
# 'oauth2_provider.ext.rest_framework.OAuth2Authentication', Deprecated
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
# social authentication
'rest_framework_social_oauth2.authentication.SocialAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
'rest_framework.permissions.IsAuthenticated',
)
OAUTH_SINGLE_ACCESS_TOKEN = True
OAUTH2_PROVIDER =
'OAUTH_SINGLE_ACCESS_TOKEN': True,
'OAUTH_DELETE_EXPIRED': True,
# 'ACCESS_TOKEN_EXPIRE_SECONDS': 24 * 60 * 60, # expires after 24 hours (default 10 hours = 36000s)
# 'ACCESS_TOKEN_EXPIRE_SECONDS': 60 * 60, # expires after 1 hour (default 10 hours = 36000s)
'ACCESS_TOKEN_EXPIRE_SECONDS': 60 * 60 * 24 * 366, # expires after 1 year
'REFRESH_TOKEN_EXPIRE_SECONDS': 60,
# this is the list of available scopes
'SCOPES':
'read': 'Read scope',
'write': 'Write scope',
'groups': 'Access to your groups'
AUTHENTICATION_BACKENDS = (
# weixin a.k.a wechat oauth2
# 'social_core.backends.weixin.WeixinOAuth2',
# vk oauth2
'social_core.backends.vk.VKOAuth2',
# Others auth providers (e.g. Google, OpenId, etc)
# Facebook OAuth2
'social_core.backends.facebook.FacebookAppOAuth2',
'social_core.backends.facebook.FacebookOAuth2',
'oauth2_provider.backends.OAuth2Backend',
# Google Oauth2
'social_core.backends.google.GoogleOAuth2',
# django-rest-framework-social-oauth2
'rest_framework_social_oauth2.backends.DjangoOAuth2',
# Django
'django.contrib.auth.backends.ModelBackend',
'oauth2_provider.backends.OAuth2Backend',
)
# fill these
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = ''
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = ''
SOCIAL_AUTH_GOOGLE_CLIENT_ID = ''
# for Gmail
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'hopster.dev@gmail.com'
EMAIL_HOST_PASSWORD = 'Hopster@123'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
这是wsgi.py文件
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hopster.settings.local")
application = get_wsgi_application()
这是错误
Traceback(最近一次调用最后一次): 文件“manage.py”,第 22 行,在 execute_from_command_line(sys.argv) 文件“F:\Python Project\Hopster Mobile Application\Test\hopster\venv\lib\site-packages\django\core\management__init__.py”,第 381 行,在 execute_from_command_line 实用程序.execute()
文件“F:\Python Project\Hopster Mobile Application\Test\hopster\venv\lib\site-packages\django\core\management__init__.py”,第 375 行,在执行中 self.fetch_command(subcommand).run_from_argv(self.argv)
文件“F:\Python Project\Hopster Mobile Application\Test\hopster\venv\lib\site-packages\django\core\management\base.py”,第 316 行,在 run_from_argv self.execute(*args, **cmd_options)
文件“F:\Python Project\Hopster Mobile Application\Test\hopster\venv\lib\site-packages\django\core\management\commands\runserver.py”,第 60 行,在执行 super().execute(*args, **options)
文件“F:\Python Project\Hopster Mobile Application\Test\hopster\venv\lib\site-packages\django\core\management\base.py”,第 353 行,在执行中 输出 = self.handle(*args, **options)
文件“F:\Python Project\Hopster Mobile Application\Test\hopster\venv\lib\site-packages\django\core\management\commands\runserver.py”,第 67 行,在句柄中 如果不是 settings.DEBUG 而不是 settings.ALLOWED_HOSTS:
getattr 中的文件“F:\Python Project\Hopster Mobile Application\Test\hopster\venv\lib\site-packages\django\conf__init__.py”,第 57 行 self._setup(name)
文件“F:\Python Project\Hopster Mobile Application\Test\hopster\venv\lib\site-packages\django\conf__init__.py”,第 44 行,在 _setup self._wrapped = 设置(settings_module)
init 中的文件“F:\Python Project\Hopster Mobile Application\Test\hopster\venv\lib\site-packages\django\conf__init__.py”,第 126 行 raise ImproperlyConfigured("SECRET_KEY 设置不能为空。")
django.core.exceptions.ImproperlyConfigured:SECRET_KEY 设置不能为空。
【问题讨论】:
您是否在配置文件中填写了 SECRET_KEY ?检查这个:***.com/questions/7382149/… dict.get() 接受一个空字符串作为值,因此如果找到一个键'secrets'
但为空,config.get('secrets', 'SECRET_KEY')
将不会回退到默认值
@J.K 是的,填写 SECRET_KEY 但仍然出现这些错误
【参考方案1】:
我认为问题出在您的manage.py
上。你的manage.py
应该是
import locale
import os
import sys
if __name__ == '__main__':
locale.setlocale(locale.LC_ALL, '')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hopster.settings.local') # Your local.py
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
'Could not import Django. Are you sure it is installed and '
'available on your PYTHONPATH environment variable? Did you '
'forget to activate a virtual environment?'
) from exc
execute_from_command_line(sys.argv)
【讨论】:
【参考方案2】:您的 manage.py 文件应该这样定义(适合实时部署):
import os
import sys
import dotenv #pip install python3-dotenv
def main():
"""Run administrative tasks."""
dotenv.load_dotenv(
os.path.join(os.path.dirname(__file__), 'config.env')
)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', "hopster.settings.local")
if os.getenv("DJANGO_SETTINGS_MODULE"):
os.environ["DJANGO_SETTINGS_MODULE"] = os.getenv("DJANGO_SETTINGS_MODULE")
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)
if __name__ == '__main__':
main()
然后创建一个文件(您的 manage.py 文件所在的位置)config.env 并在该文件中定义 SECRET_KEY。此外,定义设置模块。您的 config.env 文件应如下所示:
DJANGO_SETTINGS_MODULE = hopster.settings.local
SECRET_KEY = tantallum@tungsten...(whatever)
在您的 settings.local 文件中,将您的 SECRET_KEY 定义为:
SECRET_KEY = os.getenv("SECRET_KEY")
【讨论】:
以上是关于如何解决在 Django 中执行 manage.py runserver 命令时的错误原因?的主要内容,如果未能解决你的问题,请参考以下文章
如何解决在 Django 中执行 manage.py runserver 命令时的错误原因?