python - 在 CentOS 7/Apache 2.4/Python 3.4 上运行 Django 1.9

标签 python django apache centos

我已经在我的电脑上成功创建了我的 Django (1.9) 站点。现在正在尝试将其移动到 Web 服务器(CentOS 7)。坐了一整天,在网上搜索后,我找到了很多关于如何做到这一点的指南。但是在所有这一切之中,可能将其中一些混淆在一起,因为似乎没有使 Django 在网络服务器上运行的“单向”。

经过长时间的努力,我实际上已经设法让 Apache (2.4.6) 运行起来,但我现在看到一个内部 500 错误。我花了一段时间,但我找到了日志文件。对于我的其他读者,他们在/etc/httpd/logs/error_log 中。

[Wed Feb 24 18:00:05.475116 2016] [mpm_prefork:notice] [pid 4641] AH00163: Apache/2.4.6 (CentOS) mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations
[Wed Feb 24 18:00:05.475162 2016] [core:notice] [pid 4641] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Wed Feb 24 18:00:12.867329 2016] [:error] [pid 4642] [client x:54699] mod_wsgi (pid=4642): Target WSGI script '/var/www/sites/mysite.com/mysite/wsgi.py' cannot be loaded as Python module.
[Wed Feb 24 18:00:12.867484 2016] [:error] [pid 4642] [client x:54699] mod_wsgi (pid=4642): Exception occurred processing WSGI script '/var/www/sites/mysite.com/mysite/wsgi.py'.
[Wed Feb 24 18:00:12.867570 2016] [:error] [pid 4642] [client x:54699] Traceback (most recent call last):
[Wed Feb 24 18:00:12.867664 2016] [:error] [pid 4642] [client x:54699]   File "/var/www/sites/mysite.com/mysite/wsgi.py", line 12, in <module>
[Wed Feb 24 18:00:12.868020 2016] [:error] [pid 4642] [client x:54699]     from django.core.wsgi import get_wsgi_application
[Wed Feb 24 18:00:12.868109 2016] [:error] [pid 4642] [client x:54699] ImportError: No module named django.core.wsgi

我假设我需要对 Django 代码的某种引用,尽管我不知道为什么、如何或在哪里放置它。

出于任何 future 读者的兴趣,也为了看看我做了什么,我将尝试追溯我所做的步骤,以便能够看到我可能遗漏或做错了什么。

注意:我没有使用 virtualenv 来运行我的 Django 项目。

  1. 已安装 python 3.4
  2. 为 python 3.4 安装了 pip(使用 curl)
  3. 已安装 Apache 2.4(来自 yum)
  4. 安装了 mod_wsgi(来自 yum)(很多网站都说直接从代码编译它,但没有冒险尝试,有人强烈推荐这样做吗?)
  5. 使用 pip 安装 Django(注意,没有 virtualenv)

完成上述操作后,我使用SVN 客户端将我在服务器上的代码 check out 到文件夹/var/www/sites/mysite.com 中。文件夹结构如下所示。 (注意仍在使用 sqllite,还没有迁移到 PostgreSQL,这是下一步,一旦我看到我的网站在线)

(旁注,我花了很多时间弄清楚 Django 代码放在哪里,因为我到处看,它的位置都不一样。我最终决定直接把它放在/var/www 中,因为它是站点代码,这里似乎需要它。欢迎任何评论。)

+---var
|   \---www
|       \---sites
|          \---static
|          \---mysite.com
|             +---db.sqllite3
|             +---manage.py
|             \---.svn
|             \---mysite
|                +---settings.py
|                +---urls.py
|                +---wsgi.py
|                +---...
|             \---mysiteapp
|                +---urls.py
|                +---admin.py
|                +---...

我使用“sudo python3.4 manage.py collectstatic”将静态文件移动到/var/www/sites/static/文件夹。因为我不希望它位于我的 .svn 文件所在的文件夹中。我可以忽略该文件夹,但现在是这样。

Apache 安装非常标准,我更改了一些东西,但就我而言,应该不会有影响,所以我只是在这里显示我在“/”中使用的 conf 文件etc/httpd/conf.d”文件夹。 (请注意,我已将项目名称替换为 mysite)

WSGIPythonPath /var/www/sites/mysite.com
ServerName sub.server.com
<VirtualHost *:80>

  Alias /static/ /var/www/sites/static/
  <Directory /var/www/sites/static/>
    Options -Indexes
    Require all granted
  </Directory>

  WSGIScriptAlias / /var/www/sites/mysite.com/mysite/wsgi.py

  <Directory /var/www/sites/mysite.com/mysite>
    <Files wsgi.py>
      Require all granted
    </Files>
  </Directory>

</VirtualHost>

我的 wsgi.py 文件是 Django 在创建初始项目时创建的标准文件。这在我的计算机上运行时与 Djangos 自己的 Web 服务器一起工作,看不出我是否必须在此处更改某些内容才能使其在使用 Apache 时工作?

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = get_wsgi_application()

为了感兴趣,我还包括了 settings.py 文件,看看这里有什么。

import os

# 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.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = <removed>

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'mysiteapp.apps.mysiteappConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

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


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


# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'CET'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Logging
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'
        },
        'logfile': {
            'class': 'logging.handlers.WatchedFileHandler',
            'filename': '/var/log/django/error.log'
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django': {
            'handlers': ['logfile'],
            'level': 'ERROR',
            'propagate': False,
        },
    }
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_ROOT = '/var/www/sites/static/'
STATIC_URL = '/static/'

我希望有人能指出我正确的方向。我很感激我能得到的任何帮助,或对设置的评论。经过一整天的尝试并在网上搜索后,我真的很想念关于如何让 Django 在服务器端运行的好指南。指南太多了,但您需要将许多不同的指南组合一次才能获得全貌,因为每个指南都做出了如此多的假设,您或多或少必须具备先验知识才能使用它们。

当您组合这些指南时,每个指南的做法都略有不同,这让您的大脑加类加点地拼凑起来。 :)

最佳答案

(代表 OP 发布)。

有时候你只需要远离事物,从不同的角度来看待它。这只是一个缺少的引用。在 conf 中,我还需要添加对 Django 库的引用。我向 WSGIPythonPath 添加了“/usr/lib64/python3.4/site-packages:”,因此它现在看起来如下所示。然后一切都奏效了。我希望这至少现在可以帮助其他人。

WSGIPythonPath /usr/lib64/python3.4/site-packages:/var/www/sites/mysite

如果有人无意中看到这篇文章,并且想对我提出的任何其他问题发表评论,请随意。我仍然想知道,如果我的方法可以改进,因为这只是一个临时服务器,我必须为生产重新做一遍。还不如学习做得更好。

关于python - 在 CentOS 7/Apache 2.4/Python 3.4 上运行 Django 1.9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35609750/

相关文章:

php - 单击 drupal 主页上的链接时没有任何反应

apache - SPA 中 SEO 的 RewriteRule 不起作用

Python (pip) - RequestsDependencyWarning : urllib3 (1. 9.1) 或 chardet (2.3.0) 与支持的版本不匹配

python - 无法让我的异步函数正常工作

python - 如何将 python-django 中的列表而不是字典传递到 html 页面

python - Django:如何为允许多个文件上传的字段编写一个干净的方法?

python - IDLE 状态下跳转到特定行?

python - 在python中打印一条水平线

python - ModelForm 和 error_css_class

php - 安装 PHP 后 Apache 无法重启