无法启动 Django 游戏化服务器 - DJANGO_SETTINGS_MODULE

Unable to start Django Gamification Server - DJANGO_SETTINGS_MODULE

我的任务是在我们部门 运行 进行游戏化以激励员工。

我找到了这个 https://github.com/ngageoint/gamification-server 这是一个由 NGA 发布的开源游戏化服务器。

我已严格按照所有说明进行操作,但无法启动服务器。

一些信息:
平台 - Ubuntu 14 LTS
开始游戏化之前安装的软件包:
PostgreSQL
Python Python-开发
Git
虚拟环境

我能够安装依赖项,但是当我转到第二个任务时 "paver createdb" 我收到以下错误:

---> pavement.createdb


Captured Task Output:
---------------------

---> pavement.createdb
Traceback (most recent call last):
  File "/root/pyenv/gamification/local/lib/python2.7/site-packages/paver/tasks.p                                                                                        y", line 195, in _run_task
    return do_task()
  File "/root/pyenv/gamification/local/lib/python2.7/site-packages/paver/tasks.p                                                                                        y", line 192, in do_task
    return func(**kw)
  File "pavement.py", line 87, in createdb
    from gamification import settings
  File "/etc/gamification-server/gamification/__init__.py", line 3, in <module>
    from gamification.core.models import Points
  File "/etc/gamification-server/gamification/core/models.py", line 27, in <modu                                                                                        le>
    from django.contrib.auth.models import User
  File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/contri                                                                                        b/auth/__init__.py", line 7, in <module>
    from django.middleware.csrf import rotate_token
  File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/middle                                                                                        ware/csrf.py", line 14, in <module>
    from django.utils.cache import patch_vary_headers
  File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/utils/                                                                                        cache.py", line 26, in <module>
    from django.core.cache import caches
  File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/core/c                                                                                        ache/__init__.py", line 34, in <module>
    if DEFAULT_CACHE_ALIAS not in settings.CACHES:
  File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/conf/_                                                                                        _init__.py", line 48, in __getattr__
    self._setup(name)
  File "/root/pyenv/gamification/local/lib/python2.7/site-packages/django/conf/_                                                                                        _init__.py", line 42, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
ImproperlyConfigured: Requested setting CACHES, but settings are not configured.                                                                                         You must either define the environment variable DJANGO_SETTINGS_MODULE or call                                                                                         settings.configure() before accessing settings.

我已经按照说明配置了 settings.py 文件,并根据需要安装了所有软件包和依赖项,但完全没有任何进展。

Settings.py

import os

PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = [
    # ("Your Name", "your_email@example.com"),
]

MANAGERS = ADMINS

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql_psycopg2",
        "NAME": "gamification",
        "USER": "game_manager",
        "PASSWORD": "django-gamification",
        "HOST": "localhost",
        "PORT": "5432"
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = "UTC"

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "en-us"

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
#MEDIA_ROOT = os.path.join(PACKAGE_ROOT, "site_media", "media")

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
# MEDIA_URL = "/site_media/media/"

# Absolute path to the directory static files should be collected to.
# Don"t put anything in this directory yourself; store your static files
# in apps" "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
#STATIC_ROOT = '{0}'.format('/var/www/static')
STATIC_ROOT = os.path.join(PACKAGE_ROOT, "static")
MEDIA_ROOT = os.path.join(PROJECT_ROOT, "gamification/site_media")

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = "/static/"

# Additional locations of static files
#STATICFILES_DIRS = [
#    os.path.join(PACKAGE_ROOT, "static"),
#]

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]

# Make this unique, and don't share it with anybody.
SECRET_KEY = "z7lz3v!zl9yohg2(yfk0!cmv)#lkl6znja*hh877b&byujuu7875vfr"

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = [
    "django.template.loaders.filesystem.Loader",
    "django.template.loaders.app_directories.Loader",
]

TEMPLATE_CONTEXT_PROCESSORS = [
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.core.context_processors.request",
    "django.contrib.messages.context_processors.messages",
    "account.context_processors.account",
    "pinax_theme_bootstrap.context_processors.theme",
]


MIDDLEWARE_CLASSES = [
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
]

ROOT_URLCONF = "gamification.urls"

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = "gamification.wsgi.application"

TEMPLATE_DIRS = [
    os.path.join(PACKAGE_ROOT, "templates"),
]

REST_FRAMEWORK = {
    # hyperlinked styles by default
    # only used if the 'serializer_class' attribute is not set on view
    'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer',

    # Use Django's standard 'django.contrib.auth' permissions, or read-only for unauthorized users
    # 'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly']
}

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    # theme
    "pinax_theme_bootstrap",
    "django_forms_bootstrap",

    # external
    "account",
    "metron",
    "eventlog",
    "bootstrap3",
    "south",
    "rest_framework",
    "corsheaders",
    "mptt",

    # project
    "gamification",
    "gamification.badges",
    "gamification.core",
    "gamification.events",
]

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "filters": {
        "require_debug_false": {
            "()": "django.utils.log.RequireDebugFalse"
        }
    },
    "handlers": {
        "mail_admins": {
            "level": "ERROR",
            "filters": ["require_debug_false"],
            "class": "django.utils.log.AdminEmailHandler"
        }
    },
    "loggers": {
        "django.request": {
            "handlers": ["mail_admins"],
            "level": "ERROR",
            "propagate": True,
        },
    }
}

FIXTURE_DIRS = [
    os.path.join(PROJECT_ROOT, "fixtures"),
]

EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"

ACCOUNT_OPEN_SIGNUP = True
ACCOUNT_USE_OPENID = False
ACCOUNT_REQUIRED_EMAIL = False
ACCOUNT_EMAIL_VERIFICATION = False
ACCOUNT_EMAIL_AUTHENTICATION = False
ACCOUNT_LOGIN_REDIRECT_URL = "home"
ACCOUNT_LOGOUT_REDIRECT_URL = "home"
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 2

AUTHENTICATION_BACKENDS = [
    "account.auth_backends.UsernameAuthenticationBackend",
]

CORS_ORIGIN_WHITELIST = ( '192.168.5.131:8000', 'localhost:8000', )
CORS_ALLOW_METHODS = ( 'GET', 'POST', 'OPTIONS' )

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    }
}

更新——对于任何发现此代码并遇到同样问题的人。 在任务 createdb 和 create_db_user 下的 pavement.py 文件中,我添加了以下两行

import os
os.environ["DJANGO_SETTINGS_MODULE"]="gamification.settings"

--更新--

终于开始工作了。似乎在游戏化服务器的设置中缺少几个步骤。

在发布 Paver createdb 之前,我 运行 paver install_fixturepaver sync_initial 这为我解决了问题,服务器现在 运行 完美

更新

仔细查看堆栈跟踪,似乎存在导入设置的循环引用。

createdb 任务导入设置 >> 游戏化(初始 py 文件)导入 core.models >> 导入 django 用户 >> 导致导入设置以查找 DEFAULT_CACHE_ALIAS 。 ..

我想你最好看看这是否是游戏化服务器包的稳定版本。

原回答:

完整的错误是:

ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Django (1.8) 预先设置了 CACHES setting 所需的 'default' 后端。因此,对于普通 Django,它可以直接运行,无需声明 CACHES 设置。

对我来说,错误意味着 Django 设置对象未初始化。 settings.py 可能尚未加载(如果 paver createdb 不是 Django 管理命令,则可能)。

偶尔,当我的 settings.py 有语法错误并且没有被解释器正确解析时,我会发现这种类型的错误。您可以尝试使用 python shell 和 运行 "import settings.py" 直接查看。

好的,我自己设法解决了这个问题。如果有人找到此代码并想将其用作游戏化服务器,请按照以下步骤操作:

  1. 设置你的OS(我用的是LinuxUbuntu)
  2. 安装python、postgresql、git、pip、libpq-dev
  3. 创建并激活虚拟环境
  4. 将代码克隆到您的 cwd
  5. 安装摊铺机
  6. 安装依赖项
  7. 运行 命令摊铺机 sync_initial, 摊铺机 install_fixture
  8. 摊铺机创建b
  9. 摊铺机create_db_user
  10. python manage.py 创建超级用户
  11. python manage.py 运行服务器

这应该能让事情顺利进行。请参阅我的原始 post 以了解我对某些文件所做的更改,这也有助于正确设置服务器。

在尝试了上面的命令之后,我仍然无法使用 createdb 和 create_db_user 命令创建数据库、用户和表。所以,我开始考虑可能是权限问题。

以下内容帮助我填充了数据库(请注意,这对大多数人来说可能是显而易见的,但对我来说却并非如此)。

这些步骤适用于 Ubuntu,但我认为它们也适用于其他 Linux 类型,只要 Postgres 8.x 或更高版本,Python2.7 和VirtualEnv 已安装并正在运行。

登录 Postgres:

$ bash #=> run under bash if not already
$ export DJANGO_SETTINGS_MODULE="gamification.settings"
$ source ~/pyenv/gamification/bin/activate
$ sudo service postgresql start
$ psql -U postgres
postgres-# CREATE USER game_manager WITH PASSWORD 'supersecret';
postgres-# CREATE DATABASE gamification;
postgres=# GRANT ALL PRIVILEGES ON DATABASE gamification to game_manager;
postgres-# ALTER USER GRANT SELECT ON gamification to game_manager;
postgres-# ALTER USER GRANT INSERT ON gamification to game_manager;
postgres-# ALTER USER GRANT DELETE ON gamification to game_manager;
postgres-# ALTER USER GRANT RULE ON gamification to game_manager;
postgres=# GRANT ALL PRIVILEGES ON table-name to public; #=> this step may be unnecessary
$ python manage.py syncdb
$ python manage.py syncdb #=> run it again
$ python manage.py migrate gamification.core
$ python manage.py migrate gamification.badges
$ python manage.py migrate gamification.event
$ python manage.py migrate gamification.core #=> run it again
$ python manage.py migrate gamification.badges #=> run it again
$ python manage.py migrate gamification.events #=> run it again

忽略错误。它们(我认为)是因为上面 post 中提到的循环依赖。