使用mod_wsgi将django部署到apache

前面用mod_python搭建了django的服务器环境,http://blog.csdn.net/whoami021/article/details/14056455

可惜mod_python不更新了,所以这次把它换成mod_wsgi了。

顺便说一说,现在的部署是基于以前用mod_python的环境的。如果想直接部署mod_wsgi,可两篇文章一同参考。

首先,删除mod_enabled下的两个软连接python.confpython.load。它们是在使用mod_python方式的时候建立的。

然后安装mod_wsgi

sudo apt-get install libapache2-mod-wsgi

接着在http.conf里面加入一行:

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

加载wsgi模块。

接下来就可以测试了。

/etc/hosts里面新建一个主机wsgi.testserver

在文件里面添加一行:

192.168.1.105 wsgi.testserver

注意ip地址要写本机地址,我就是在这里搞了好久。应该直接用localhost也可以的。

切换到/var/www下面,创建工程目录wsgi,新建文件main.wsgi

输入代码:

def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'
 
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
 
    return [output]

然后去apache的配置目录/etc/apache2/sites-available,新建一个网站的配置文件wsgi并输入如下内容:

<VirtualHost *:80>
 
    ServerName wsgi.testserver
    DocumentRoot /var/www/wsgi
 
    <Directory /var/www/wsgi>
        Order allow,deny
        Allow from all
    </Directory>
 
    WSGIScriptAlias / /var/www/wsgi/main.wsgi
 
</VirtualHost>

激活网站:

sudo a2ensite wsgi  #wsgi就是刚刚在sites-available目录下创建的文件名称.

加载网站:

sudo service apache2 reload

这时候打开浏览器,输入http://wsgi.testserver,你就会看到HelloWorld

接下来配置django

django项目的根目录创建文件django.wsgi,让apache知道wsgi的存在。

输入内容:

#coding: utf-8
import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] ='mysite.settings'

os.environ['PYTHON_EGG_CACHE'] = '/tmp/.python-eggs'

current_dir = os.path.dirname(__file__)
if current_dir not in sys.path:
    sys.path.append(current_dir)

import django.core.handlers.wsgi

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

接着在sites-available目录下创建一个新的站点mysite,也就是创建一个文件mysite,输入内容:

<VirtualHost *:80>

    ServerName mysite.com

    DocumentRoot /home/michael/workspace/web/djcode/mysite

    <Directory "/">
        Order allow,deny
        Allow from all
    </Directory>

    WSGIScriptAlias / /home/michael/workspace/web/djcode/mysite/apache/django.wsgi

</VirtualHost>

然后在/etc/hosts里面新建一个主机mysite.com,就像上面新建主机wsgi.testserver一样。

激活站点,重启apache

sudo a2ensite mysite

sudo service apache2 restart

打开浏览器,输入mysite.com,就可以看到你建立的网站了。

补充一下,如果更新了网站内容,只要重新加载服务器就好了:sudo service apache2 reload

如果觉得生产环境下开发太麻烦,每次更新都要reload一次,只要停止apache服务,然后启动django自带的服务器就可以了。

sudo service apache2 stop

python manage.py runserver


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值