无法启动Django Gamification Server - DJANGO_SETTINGS_MODULE

时间:2015-04-22 07:50:34

标签: python linux django postgresql psycopg2

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

我发现这是https://github.com/ngageoint/gamification-server这是NGA发布的开源游戏化服务器。

我已按照所有说明写信,但无法启动服务器。

一些信息:
平台 - Ubuntu 14 LTS
在游戏化开始之前安装的软件包:
PostgreSQL的
Python Python-dev
Git的
VIRTUALENV

我能够安装依赖项,但是当我进入第二个任务时#34; 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文件中,我添加了以下2行

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

- UPDATE -

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

在发布Paver createdb之前,我运行了paver install_fixturepaver sync_initial这对我进行了整理,服务器现在运行正常

3 个答案:

答案 0 :(得分:2)

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

  1. 设置您的操作系统(我使用的是Linux Ubuntu)
  2. 安装python,postgresql,git,pip,libpq-dev
  3. 创建并激活虚拟环境
  4. 将代码克隆到您的cwd
  5. 安装Paver
  6. 安装依赖项
  7. 运行命令摊铺机sync_initial,摊铺机install_fixture
  8. Paver createdb
  9. Paver create_db_user
  10. python manage.py createsuperuser
  11. python manage.py runserver
  12. 这应该让事情顺利进行。请参阅我的原始帖子,了解我对某些文件所做的更改,这些更改也有助于正确设置服务器。

答案 1 :(得分:2)

在使用上述命令后,我仍然无法使用createdb和create_db_user命令创建数据库,用户和表。所以,我开始认为这可能是一个权限问题。

以下帮助我填充了数据库(注意这对大多数人来说可能是显而易见的,但不适合我)。

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

登录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

忽视错误。它们(我认为)是因为上面帖子中提到的循环依赖性。

答案 2 :(得分:1)

<强>更新

仔细观察堆栈跟踪,似乎有循环引用来导入设置。

createdb任务导入设置&gt;&gt;游戏化(init py文件)导入core.models&gt;&gt;导入django用户&gt;&gt;导致导入设置以查找DEFAULT_CACHE_ALIAS ...

我认为你最好看看这是否是Gamification Server软件包的稳定版本。

原始回答:

完整错误是:

  

NotperlyConfigured:请求设置CACHES,但设置不是   配置。您必须定义环境变量   DJANGO_SETTINGS_MODULE或在访问之前调用settings.configure()   设置。

Django(1.8)预设了CACHES setting所需的“默认”后端。因此,对于vanilla Django,它可以直接运行,不会声明CACHES设置。

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

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