Django/Apache 设置给我一个 'module not found' 错误

Django/Apache setup giving me a 'module not found' error

所以我有这个 AngularJS/Django/Apache 项目,我在过去的员工离开后被投入其中。到目前为止,一切都非常简单,但我正在努力让 Django/Apache 一起玩得很好,但它没有用。

因为它是 'module not found error' 是否有可能由于某种原因在路径上找不到 my_report 目录,或者存在权限错误?

我通常是一名 Java/MySql 开发人员,我习惯 Python 作为后端脚本语言,所以这对我来说有点新鲜 :P

整个项目位于 /var/www/html/CoreRubrics/DjangoBackend 目录中,结构如下。

drwxr-xr-x. 2 apache users   5 Apr 21 16:01 CourseLists
-rw-r--r--. 1 apache users 250 Apr 21 16:01 manage.py
drwxr-xr-x. 2 apache users   4 Apr 21 16:01 scripts
drwxr-xr-x. 3 apache users  14 Apr 21 16:30 my_report
drwxr-xr-x. 2 apache users   3 Apr 21 17:04 apache
drwxr-xr-x. 2 apache users   8 Apr 23 11:19 my_proj

我有 apache 服务于前端 AngularJS 非常好,但是 Apache 在日志中给我以下错误。

[Thu Apr 23 11:15:23.230040 2015] [:info] [pid 15039] [client 172.16.75.13:57216] mod_wsgi (pid=15039, process='', application='<<url goes here>>|/corerubric/cr'): Loading WSGI script '/var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi'., referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803198 2015] [:error] [pid 15039] [client 172.16.75.13:57216] mod_wsgi (pid=15039): Target WSGI script '/var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi' cannot be loaded as Python module., referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803253 2015] [:error] [pid 15039] [client 172.16.75.13:57216] mod_wsgi (pid=15039): Exception occurred processing WSGI script '/var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi'., referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803304 2015] [:error] [pid 15039] [client 172.16.75.13:57216] Traceback (most recent call last):, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803346 2015] [:error] [pid 15039] [client 172.16.75.13:57216]   File "/var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi", line 12, in <module>, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803670 2015] [:error] [pid 15039] [client 172.16.75.13:57216]     application = get_wsgi_application(), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803704 2015] [:error] [pid 15039] [client 172.16.75.13:57216]   File "/usr/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803784 2015] [:error] [pid 15039] [client 172.16.75.13:57216]     django.setup(), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803816 2015] [:error] [pid 15039] [client 172.16.75.13:57216]   File "/usr/lib/python2.7/site-packages/django/__init__.py", line 21, in setup, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804003 2015] [:error] [pid 15039] [client 172.16.75.13:57216]     apps.populate(settings.INSTALLED_APPS), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804044 2015] [:error] [pid 15039] [client 172.16.75.13:57216]   File "/usr/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804376 2015] [:error] [pid 15039] [client 172.16.75.13:57216]     app_config = AppConfig.create(entry), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804413 2015] [:error] [pid 15039] [client 172.16.75.13:57216]   File "/usr/lib/python2.7/site-packages/django/apps/config.py", line 87, in create, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804624 2015] [:error] [pid 15039] [client 172.16.75.13:57216]     module = import_module(entry), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804656 2015] [:error] [pid 15039] [client 172.16.75.13:57216]   File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804744 2015] [:error] [pid 15039] [client 172.16.75.13:57216]     __import__(name), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804797 2015] [:error] [pid 15039] [client 172.16.75.13:57216] ImportError: No module named my_report, referer: <<url goes here>>/

这是 .wsgi 文件:

import os
import sys
from django.core.wsgi import get_wsgi_application

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

path='/var/www/html/CoreRubrics/DjangoBackend/my_proj'
if path not in sys.path:
        sys.path.append(path)


application = get_wsgi_application()

所以我尝试了 运行:

python /var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi

然后我得到这个错误:

Traceback (most recent call last):
  File "/var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi", line 12, in <module>
    application = get_wsgi_application()
  File "/usr/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application
    django.setup()
  File "/usr/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/usr/lib/python2.7/site-packages/django/apps/config.py", line 87, in create
    module = import_module(entry)
  File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named my_report

这是我的 settings.py

# Django settings for my_proj project.
from mongoengine import connect
connect(<<super secret DB stuff>>)

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    ('William Karavites', 'willkara@oit.rutgers.edu'),
)

MANAGERS = ADMINS

#DATABASES = {
#    'default': {
       # 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        #'NAME': '',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        #'USER': '',
        #'PASSWORD': '',
        #'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        #'PORT': '',                      # Set to empty string for default.
   # }
#}

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

# 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.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/New_York'

# 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: "/var/www/example.com/media/"
MEDIA_ROOT = ''

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

# 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: "/var/www/example.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# 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',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '<super secret secret>'

# 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',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    #'django.contrib.auth.middleware.RemoteUserMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

#AUTHENTICATION_BACKENDS = (
#    'django.contrib.auth.backends.RemoteUserBackend',
#)

ROOT_URLCONF = 'my_proj.urls'

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

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
   #  'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
     'django.contrib.admindocs',
    'mongoengine.django.mongo_auth',
    'my_report',
)
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User'
SESSION_ENGINE = 'mongoengine.django.sessions'

# 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,
        },
    }
}

Aaaaaa 以防万一,这是我的站点的 apache .conf 文件:

#modified from anaylitics:/etc/httpd/conf.d/apache.conf
#<Directory /home/kimhuang/my_proj/apache>
#Order deny,allow
#Allow from all
#</Directory>

#WSGIPythonHome /home/kimhuang/my_proj_env
WSGIPythonPath /var/www/html/CoreRubrics/DjangoBackend/my_proj/:/var/www/html/CoreRubrics/DjangoBackend/my_report/
#WSGIScriptAlias /cr /home/kimhuang/my_proj/apache/django.wsgi

<VirtualHost <<ip>>>
    ServerName <<url>>
    ServerAlias <<url>>
        <Location "/">
        Order Allow,Deny
        Allow from all
    </Location>
    DocumentRoot /var/www/html/CoreRubrics/FrontEnd

    WSGIScriptAlias /corerubric/cr /var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi

    ErrorLog logs/corerubrics_error_log
        LogLevel debug
        CustomLog logs/corerubrics_access_log combined

    <Directory /var/www/html/CoreRubrics/DjangoBackend/apache/>
        <Files django.wsgi>
            Require all granted
        </Files>
    </Directory>

</VirtualHost>

my_report 应用不在项目路径中。

更改 wsgi 文件中的以下行:

os.environ['DJANGO_SETTINGS_MODULE'] = 'my_proj.settings'

path='/var/www/html/CoreRubrics/DjangoBackend/'

您可能应该阅读有关正确项目结构的内容,因此这里有一些资源:

my_report 应该是 sys.path 下的任何一个包或模块。

首先,确保 sys.path 中有 /var/www/html/CoreRubrics/DjangoBackend,因为 my_report 可以在那里找到。

其次,如果my_report是一个包,确保它下面有__init__.py文件。