使用Apache和mod_wsgi部署Django应用

1.安装Apache

yum install httpd httpd-devel

2.在项目虚拟环境安装mod_wsgi

注意:使用python3.7版本在安装时会报错,需要重新编译

.1) 进入python对应版本解压路径
cd /opt/Python-3.7.6
.2) 重新编译(末尾加--enable-shared)
./configure --prefix=/root/.local/share/virtualenvs/zanhu-qCBWC76o/ --enable-shared
.3) 编译完成后,将虚拟环境目录lib文件夹下的libpython3.7m.so.1.0文件拷贝至/usr/lib64/目录下
cp /root/.local/share/virtualenvs/zanhu-qCBWC76o/lib/libpython3.7m.so.1.0 /usr/lib54/

此时再进入虚拟环境可以完成安装

pip install mod_wsgi

3.导出模块

(zanhu) [root@192 zanhu]# mod_wsgi-express install-module
LoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so"
WSGIPythonHome "/root/.local/share/virtualenvs/zanhu-qCBWC76o"

4.将上面的LoadModule配置写入Apache的配置文件

vim /etc/httpd/conf/httpd.conf
# 添加下面两句
LoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so"
ServerName 127.0.0.1

此时再启用Apache服务,通过F12查看Response Header的Server如下,说明Python3.7解释器已经成功应用

Server: Apache/2.4.6 (CentOS) mod_wsgi/4.7.1 Python/3.7

5.在、etc/httpd/conf.d目录下创建编辑django.conf文件

vim /etc/httpd/conf.d/django.conf
<VirtualHost *:80>
    ServerName localhost

    Alias /static/ /root/zanhu/zanhu/staticfiles/
    Alias /media/ /root/zanhu/zanhu/media/

    <Directory /root/zanhu/zanhu/staticfiles>
        Require all granted
    </Directory>

    <Directory /root/zanhu/zanhu/media>
        Require all granted
    </Directory>

    <Directory /root/zanhu/config>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess zanhu python-path=/root/.local/share/virtualenvs/zanhu-qCBWC76o/lib/python3.7/site-packages
    WSGIScriptAlias / /root/zanhu/config/wsgi.py

6.重启Apache,项目成功运行

systemctl restart httpd

日志位置:/var/log/httpd/, 目前只是在root账户下配置,没有出现权限问题,只是在使用django compressor时生成的静态压缩文件时要给代理服务器apache写的权限chmod apache:apache CACHE

上一篇:Python 中的 HTTP 服务器


下一篇:在windows下,使用apache部署django,访问接口一直pending