如何在apache2中运行Django应用程序

1 投票
3 回答
985 浏览
提问于 2025-04-16 13:20

大家好,我在Apache2服务器上运行Django应用时遇到了问题。虽然我看过所有的文档,但还是没能成功。这是我的Apache2的httpd.conf文件:

<Location "/mysite/">
  SetHandler python-program
  PythonHandler django.core.handlers.modpython
  SetEnv DJANGO_SETTINGS_MODULE mysite.settings
  PythonOption django.root /mysite
  PythonPath "['/home/djangotest/mysite'] + sys.path"
  PythonDebug On
</Location>

我的Django项目位于/home/djangotest/mysite,我在这里运行一个叫做polls的应用。请问我需要在settings.py或urls.py中做什么设置才能让它在Apache2上正常工作?在开发服务器上运行是没问题的。或者说,我需要在Apache2中做什么配置才能让它工作?

3 个回答

2
  1. 下载并安装 http://modwsgi.googlecode.com/files/mod_wsgi-3.3.tar.gz

  2. 把它放到 /etc/httpd/conf.d/ 这个文件夹里


<VirtualHost *:80>
  ServerName --insert--

  ErrorLog /home/djangotest/mysite/error_log
  CustomLog /home/djangotest/mysite/access_log combined

  UseCanonicalName Off

  WSGIScriptAlias /g2 /home/djangotest/mysite/mysite.wsgi
  WSGIDaemonProcess iproj processes=7 threads=1 display-name=%{GROUP}

</VirtualHost>
  1. 在 /etc/httpd/conf/httpd.conf 文件的 LoadModules 部分添加以下内容:

    LoadModule wsgi_module /usr/lib/httpd/modules/mod_wsgi.so

  2. 在 /etc/httpd/conf/httpd.conf 文件的 AddHandler 部分添加以下内容:

    AddHandler wsgi-script .wsgi

  3. 确保 httpd 用户可以访问 /home/djangotest/ 文件夹,并且能够执行你的 Python 脚本

  4. 创建一个 mysite.wsgi 文件:


import os
import sys

sys.path.append('/home/djangotest/mysite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

或者像 @Efazati 说的,看看手册吧;)


希望这能解决你最后的问题:

没有名为 mysite.urls 的模块,但确实有一个文件 urls.py

检查你的设置文件,看看里面是否有:

ROOT_URLCONF = "mysite.urls"

这就是你的 urls 文件的名字,我猜你没有一个叫 mysite.urls.py 的模块?听起来你的设置应该是:

ROOT_URLCONF = "urls"

1

试着把 '/home/djangotest' 加到 PythonPath 里:

<Location "/mysite/">

  SetHandler python-program
  PythonHandler django.core.handlers.modpython
  SetEnv DJANGO_SETTINGS_MODULE mysite.settings
  PythonOption django.root /mysite
  PythonPath "['/home/djangotest', '/home/djangotest/mysite'] + sys.path"

  PythonDebug On
</Location>

如果你用 .. 这种方式导入你项目里的文件,就需要加这个。这里的其他人说得对;如果可以的话,换成 mod-wsgi。因为 Django 对 mod_python 的支持很快就要停止了。http://docs.djangoproject.com/en/1.2/howto/deployment/modpython/

补充:在 Django 1.3 中,mod_python 的支持已经被停止,并且在 Django 1.5 中会完全移除。

撰写回答