简体   繁体   English

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

[英]Running Django 1.9 on CentOS 7/Apache 2.4/Python 3.4

I have successfully created my Django (1.9) site on my computer. 我已经在计算机上成功创建了Django(1.9)网站。 And is now trying to move it to a web server (CentOS 7). 现在正在尝试将其移至Web服务器(CentOS 7)。 After sitting a whole day, searching the web, I have found many guides on how to do this. 经过一整天的搜索,在网络上找到了许多有关此操作的指南。 But in the midst of all of this, probably confused some of them together, since it seems there is no "one-way" to make Django run on a webserver. 但是在所有这些之中,可能会使其中一些混淆在一起,因为似乎没有“单向”的办法可以使Django在Web服务器上运行。

After a long struggle, I have actually managed to get the Apache (2.4.6) running, but I am now seeing an Internal 500 error. 经过长时间的努力,我实际上设法使Apache(2.4.6)运行,但是现在看到内部500错误。 I took a while but i found the log files. 我花了一段时间,但找到了日志文件。 For other readers in my case they were in /etc/httpd/logs/error_log. 对于我而言,其他读者则在/ 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

I assume I need some kind of reference to the Django code, though I cannot figure out why, how or where to put this. 我假设我需要某种对Django代码的引用,尽管我无法弄清楚为什么,如何或在哪里放置它。

Out of interest of any future readers, and also to see what I have done, I will try to retrace my steps I have done to be able to see what I might have missed or done incorrectly. 出于对将来任何读者的兴趣,并查看我所做的事情,我将尝试回顾我所做的步骤,以便能够看到我可能错过或做错的事情。

NB: I am not using virtualenv to run my Django project. 注意:我没有使用virtualenv运行我的Django项目。

  1. Installed python 3.4 已安装python 3.4
  2. Installed pip for python 3.4 (using curl) 为python 3.4安装了pip(使用curl)
  3. Installed Apache 2.4 (from yum) 已安装Apache 2.4(来自yum)
  4. Installed mod_wsgi (from yum) (many sites said to compile it directly from code, did not venture into this, anyone recommending highly to do this?) 安装了mod_wsgi(来自yum)(许多站点据说直接从代码中进行编译,没有冒险尝试,有人强烈建议这样做吗?)
  5. Installed Django with pip (NB, without virtualenv) 用pip安装Django(NB,不带virtualenv)

After the above was done, I used SVN client to checkout my code on the server to the folder /var/www/sites/mysite.com. 完成上述操作后,我使用SVN客户端将服务器上的代码签出到/var/www/sites/mysite.com文件夹中。 Folder structure looks like this. 文件夹结构如下所示。 (Note still using sqllite, did not get to the migration to PostgreSQL yet, this is next step, once i see my site online) (请注意,仍在使用sqllite,尚未迁移到PostgreSQL,这是下一步,一旦我在线查看我的网站)

(Side note, I spend a lot of time figuring out where to put the Django code, since everywhere i looked, it was placed differently. I ended up deciding to put it directly in the /var/www since it is the site code, and it is needed here, it seems. Any comments are welcome.) (请注意,我花了很多时间弄清楚将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
|                +---...

I have used "sudo python3.4 manage.py collectstatic" to move the static files to the /var/www/sites/static/ folder. 我已经使用“ sudo python3.4 manage.py collectstatic”将静态文件移动到/ var / www / sites / static /文件夹。 Since I did not want this to be inside the folder where my .svn files are. 由于我不希望它位于我的.svn文件所在的文件夹中。 I could ignore the folder, but for now this is how it is. 我可以忽略该文件夹,但目前情况如此。

The Apache installations is pretty much standard, I have changed a few things, but not something which should have an impact, as far as I am concerned, so I am just showing here the conf file I am using in the "/etc/httpd/conf.d" folder. 就我而言,Apache的安装几乎是标准的,就我而言,我已经更改了一些内容,但没有更改应有影响的内容,因此,我仅在此处显示我在“ / etc / httpd”中使用的conf文件。 /conf.d”文件夹。 (please note I have replace name of the project with mysite) (请注意,我已将项目名称替换为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>

My wsgi.py file is the standard one which Django creates when creating the initial project. 我的wsgi.py文件是Django在创建初始项目时创建的标准文件。 This works with Djangos own web server when running on my computer, could not see if I might have to change something here to make it work when using Apache? 这在我的计算机上运行时可与Django自己的Web服务器一起使用,无法查看是否可能需要在此处进行某些更改才能使其在使用Apache时正常工作?

import os

from django.core.wsgi import get_wsgi_application

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

application = get_wsgi_application()

For the interested I have also included the settings.py file, to see what is here. 对于感兴趣的人,我还包括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/'

I hope someone can point me in the right direction. 我希望有人能指出我正确的方向。 I appreciate any help I can get, or comments to the setup. 感谢您能获得的任何帮助或对安装程序的评论。 After a full day of trying to make this work, and searching the web, I really miss a good guide on how to make Django run on the server side. 经过一整天的尝试,并在网上搜索之后,我真的很想念一个很好的指南,说明如何使Django在服务器端运行。 There are so many guides, but you need to combine a lot of different once to get the full picture, since each guide makes so many assumptions, and you more or less have to have prior knowledge to use them. 指南太多了,但是您一次需要将很多不同的指南组合在一起才能获得全面的了解,因为每个指南都做出了如此多的假设,您或多或少必须具备使用它们的先验知识。

And when you do combine the guides, each guide is doing it a bit differently, making your brain work overtime to piece it all together. 而且,当您合并这些指南时,每个指南的操作方式都会有所不同,使您的大脑需要加班才能将它们拼凑在一起。 :) :)

(Posted on behalf of OP). (代表OP发布)。

Sometimes you just need to go away from things, and view it from a different angle. 有时,您只需要远离事物,并从另一个角度来看待它。 It was just a reference that was missing. 它只是缺少的参考。 In the conf I needed to also add the reference to the Django libs. 在conf中,我还需要添加对Django库的引用。 To the WSGIPythonPath I added "/usr/lib64/python3.4/site-packages:", so it now looks like the below. 我在WSGIPythonPath中添加了“ /usr/lib64/python3.4/site-packages:”,因此现在看起来如下所示。 And then it all worked. 然后所有的工作。 I hope this at least now will help someone else out there. 我希望至少现在可以帮助其他人。

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

If anyone stumbles across this post, and feels like commenting on any of the other questions I have asked, please feel free. 如果有人偶然发现了这篇文章,并且想评论我所问的其他任何问题,请随意。 I would still like to know, if my approach could be improved, as this is just a staging server, and I have to do it all again for production. 我仍然想知道,是否可以改进我的方法,因为这只是一个登台服务器,我必须为生产再次进行所有操作。 Might as well learn to do it better. 最好学会做得更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM