django 部署在 apache2 上面

How to use Django with Apache and mod_wsgi

一、编译安装 mod_wsgi

源代码下载(github)
编译步骤文档
Installation Issues 文档
为了编译安装 mod_wsgi 我们需要安装python完全版(即包括python头文件)。但是在很多linux发行版中,python运行时和python开发包是分开的,而且python开发包默认不安装。
这就导致在编译的时候,可能会产生丢失头文件的错误,像下面这样的报错:

mod_wsgi.c:113:20: error: Python.h: No such file or directory
mod_wsgi.c:114:21: error: compile.h: No such file or directory
mod_wsgi.c:115:18: error: node.h: No such file or directory
mod_wsgi.c:116:20: error: osdefs.h: No such file or directory
mod_wsgi.c:119:2: error: #error Sorry, mod_wsgi requires at least Python 2.3.0.
mod_wsgi.c:123:2: error: #error Sorry, mod_wsgi requires that Python supporting thread.

为了解决这个问题,我们需要安装Python开发包,一般为你linux系统上python运行时的包名加上-dev结尾,比如:python3-dev

二、安装django,创建项目

先在终端中使用venv创建一个虚拟环境。

python -m venv v-test

然后使用pip安装django

pip install django

接着使用django-admin创建新项目

django-admin startproject showInfo

对项目进行设置并创建一个应用

python manage.py migrate
python manage.py startapp blog
...

三、配置/conf/http.conf

如果你还没有安装,参考:ubuntu 编译安装 apache2.4.46
ubuntu 使用 apt 安装 apache2

在conf/httpd.conf中添加以下配置:

WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py
WSGIPythonHome /path/to/venv
WSGIPythonPath /path/to/mysite.com

<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>

WSGIScriptAlias 指向你项目的wsgi文件
WSGIPythonHome 指向你的venv虚拟环境
WSGIPythonPath 指向你虚拟环境下的项目根目录
<Directory /path/to/mysite.com/mysite> 指向你虚拟环境下项目根目录下的项目同名目录

配置例图:

访问相应路径即可查看:

如果访问显示500错误,多半是你配置有问题,
如果访问显示403权限错误,则在conf/httpd.conf中将 Require All denied 改为 Require All granted即可。

posted @ 2020-12-20 16:28  那个白熊  阅读(468)  评论(0编辑  收藏  举报