【问题标题】:Unable to start Django Gamification Server - DJANGO_SETTINGS_MODULE无法启动 Django 游戏服务器 - DJANGO_SETTINGS_MODULE
【发布时间】:2015-06-29 17:26:08
【问题描述】:

我的任务是在我们部门启动并运行 Gamification 以激励员工。

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

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

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

我能够安装依赖项,但是当我转到第二个任务“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"

--更新--

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

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

【问题讨论】:

    标签: python linux django postgresql psycopg2


    【解决方案1】:

    在使用了上面的命令之后,我仍然无法使用 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
    

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

    【讨论】:

    • 我还发现您可以运行命令 sync_initial 并安装将为您创建数据库和表的夹具。如果您查看 pavement 文件,您会看到一堆额外的命令,这些命令未在原始操作指南中列出。我正忙于研究更详细的操作方法,我将分享。
    【解决方案2】:

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

    1. 设置您的操作系统(我使用的是 Linux Ubuntu)
    2. 安装python、postgresql、git、pip、libpq-dev
    3. 创建和激活虚拟环境
    4. 将代码克隆到您的 cwd
    5. 安装摊铺机
    6. 安装依赖项
    7. 运行命令 paver sync_initial、paver install_fixture
    8. 摊铺机创建b
    9. 摊铺机 create_db_user
    10. python manage.py createsuperuser
    11. python manage.py runserver

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

    【讨论】:

      【解决方案3】:

      更新

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

      createdb 任务导入设置 >> 游戏化(init py 文件)导入 core.models >> 导入 django 用户 >> 导致要导入的设置查找 DEFAULT_CACHE_ALIAS ...

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

      原答案:

      完整的错误是:

      ImproperlyConfigured:请求设置 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”来直接检查。

      【讨论】:

      • 我已经更新了我的原始帖子以显示我的设置文件的内容
      • settings.py 是否存在于预期路径中?您可能会通过以下方式反复试验:1)重命名设置文件以检查它是否在正确的路径上被读取,2)剥离您对设置文件所做的任何更改/自定义,直到它起作用。
      • 我现在查看了 paver 用来执行任务的 pavement 文件,createdb 任务从游戏化文件夹中导入设置,然后开始尝试在 postgres 中创建数据库
      • python 解释器可能是这里的问题吗?我在 Pycharm 中加载了代码并看到错误“Python 2.7 没有内置模块”
      • 我个人认为开发人员的说明有点模糊。我还必须在每个摊铺机任务中定义 django 设置。我用所有的细节更新了我原来的帖子。
      猜你喜欢
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      • 2021-08-30
      相关资源
      最近更新 更多