您的位置:首页 > 运维架构 > Apache

使用mod_wsgi将django部署到apache

2014-02-11 18:53 597 查看
前面用mod_python搭建了django的服务器环境,/article/2415850.html
可惜mod_python不更新了,所以这次把它换成mod_wsgi了。
顺便说一说,现在的部署是基于以前用mod_python的环境的。如果想直接部署mod_wsgi,可两篇文章一同参考。
首先,删除mod_enabled下的两个软连接:python.conf和python.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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: