gpt4 book ai didi

python - django.core.exceptions.ImproperlyConfigured : Set the DATABASE_URL environment variable

转载 作者:行者123 更新时间:2023-12-05 03:31:57 28 4
gpt4 key购买 nike

我使用 AlpacaTag 注释文本数据(为命名实体识别模型构建数据集),它是在 Django 上使用 Python 设计的。我按照 AlpacaTag 的步骤操作安装指南当我运行命令时
python manage.py 迁移
(我是来找资料的,才知道这是Django的数据库迁移命令),
程序抛出异常:

Traceback (most recent call last):
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/environ/environ.py", line 367, in get_value
value = self.ENVIRON[var]
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'SECRET_KEY'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 86, in wrapped
saved_locale = translation.get_language()
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 254, in get_language
return _trans.get_language()
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__
if settings.USE_I18N:
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 82, in __getattr__
self._setup(name)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 69, in _setup
self._wrapped = Settings(settings_module)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 170, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/home/duzx21/miniconda3/envs/alpacatag/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/duzx21/AlpacaTag/annotation/AlpacaTag/app/settings.py", line 33, in <module>
SECRET_KEY = env('SECRET_KEY')
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/environ/environ.py", line 179, in __call__
parse_default=parse_default
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/environ/environ.py", line 371, in get_value
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable

这是在setting.py文件中定义的:

SECRET_KEY = env('SECRET_KEY') 

不知道怎么解决这个问题,于是随机生成一串文字作为SECRET_KEY:

SECRET_KEY='2ap4_#)wk@5)3lsh6idzxwaouy6)*(5z#w(3atk0%a5!+-29j-'

这似乎有效。但是,当我再次运行命令时:

python manage.py migrate 

程序抛出另一个非常相似的异常:

Traceback (most recent call last):
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/environ/environ.py", line 367, in get_value
value = self.ENVIRON[var]
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'SECRET_KEY'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 86, in wrapped
saved_locale = translation.get_language()
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 254, in get_language
return _trans.get_language()
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__
if settings.USE_I18N:
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 82, in __getattr__
self._setup(name)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 69, in _setup
self._wrapped = Settings(settings_module)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 170, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/home/duzx21/miniconda3/envs/alpacatag/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/duzx21/AlpacaTag/annotation/AlpacaTag/app/settings.py", line 33, in <module>
SECRET_KEY = env('SECRET_KEY')
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/environ/environ.py", line 179, in __call__
parse_default=parse_default
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/environ/environ.py", line 371, in get_value
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
(alpacatag) duzx21@d01:~/AlpacaTag/annotation/AlpacaTag$ python manage.py migrate
Traceback (most recent call last):
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/environ/environ.py", line 367, in get_value
value = self.ENVIRON[var]
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'DATABASE_URL'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 86, in wrapped
saved_locale = translation.get_language()
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 254, in get_language
return _trans.get_language()
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__
if settings.USE_I18N:
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 82, in __getattr__
self._setup(name)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 69, in _setup
self._wrapped = Settings(settings_module)
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 170, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/home/duzx21/miniconda3/envs/alpacatag/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/duzx21/AlpacaTag/annotation/AlpacaTag/app/settings.py", line 96, in <module>
'default': env.db(),
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/environ/environ.py", line 280, in db_url
self.get_value(var, default=default),
File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/environ/environ.py", line 371, in get_value
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable

这是在setting.py文件中定义的:

    DATABASES = {
'default': env.db(),

}

我试图将 DATABASE['default'] 更改为

'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}

程序似乎可以运行,然后我运行命令

python manage.py migrate

有效!然后我运行命令

python manage.py createsuperuser

然后,输入管理员用户名和电子邮件地址以及密码,然后按回车键。

    Username: admin
Email address: admin@example.com
Password: **********
Password (again): *********

然后我运行命令

python manage.py runserver 8080

可以打开Web界面,按照作者的说法应该是:
enter image description here
但我的是:
enter image description here
我不能在上面做任何事情,比如创建一个项目,上传一个数据集,这些是它最基本的功能。
所以我之前对程序的修改应该是不正确的
这是我的设置.py:

    """
Django settings for AlpacaTag project.

Generated by 'django-admin startproject' using Django 1.11.20.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os
import environ
from pathlib import Path
from django.core.exceptions import ImproperlyConfigured
import dj_database_url


env = environ.Env()
# reading .env file
environ.Env.read_env()

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoprojeckt.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
# SECRET_KEY='2ap4_#)wk@5)3lsh6idzxwaouy6)*(5z#w(3atk0%a5!+-29j-'

# SECURITY WARNING: don't run with debug turned on in production!
# False if not in os.environ
DEBUG = env.bool('DEBUG', False)

ALLOWED_HOSTS = ['*']

# Application definition
INSTALLED_APPS = [
'server.apps.ServerConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'django_filters',
'widget_tweaks',
]

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 = 'app.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]

STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'server/static'),
]

WSGI_APPLICATION = 'app.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
# Parse database connection url strings like psql://user:pass@127.0.0.1:8458/db
DATABASES = {
# read os.environ['DATABASE_URL'] and raises ImproperlyConfigured exception if not found
'default': env.db(),
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/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',
# },
]

REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 5,
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
'SEARCH_PARAM': 'q',
}
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/projects/'
LOGOUT_REDIRECT_URL = '/'
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

我尝试学习Django的基础知识,但我对Web开发、数据库一无所知,看了一些Django的基础知识后,我仍然不知道如何调试这个错误。

最佳答案

在您的 settings.py 中,它使用 env.db(),它是 db_url() 的别名。所以你需要在 settings.py 附近有一个 .env 文件,并在该文件中为 DATABASE_URL 设置一个键。我更喜欢采用更简单的方法。所以替换这部分:

DATABASES = {
# read os.environ['DATABASE_URL'] and raises ImproperlyConfigured exception if not found
'default': env.db(),
}

用这个:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

您的 settings.py 的问题是它没有指定 STATIC_ROOT 并且由于 DEBUG=False,提供静态文件会导致您一些错误(因为您需要 collectstatic 文件,这就是您的浏览器以不同方式显示首页的原因)。我现在建议您在本地运行它,在您的 settings.py 中执行此操作:

# Search for Debug in your settings and replace with this
DEBUG = True
# Add this one to your settings
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

关于python - django.core.exceptions.ImproperlyConfigured : Set the DATABASE_URL environment variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70547798/

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