现在的位置: 首页 > 综合 > 正文

手把手教你:Ubuntu14+apache+django配置网页项目

2018年05月18日 ⁄ 综合 ⁄ 共 8196字 ⁄ 字号 评论关闭

转裁源于:

http://blog.chinaunix.net/uid-23500957-id-3838223.html

分类: LINUX

原文地址:django 1.5.1 apache2
wsgi 配置教程
 作者:bailiangcn

      之前有篇文档写到,django 的 apache 部署很恶心,我没太明白什么意思,实际自己操作时,才深有体会,恶心的意思是:明明感觉很简单,看别人的文档也挺短,但如果新手可能要弄1、2天才行,而且最关键的是毫无成就感。原因是变数太多:

  • 文档的时效性
  • 平台环境
  • 软件环境
  • 目标的目录配置
  • 主机域名等的设置

    ...

      这些的不同,造成软件的部署过程总是磕磕绊绊。为了降低挫折感,本文通过分步骤试验逐渐实现最终目标。

参考文档:

  1. django+wsgi 我是照着这篇首次成功的
  2. apache 配置文档

  3. apache2 ubuntu环境配置

软件环境

  • ubuntu 12.04 64位
  • python 2.7.3
  • django 1.5.1
  • apache 2.2
  • mod_wsgi 3.3

目标

  1. 在 ~/firstdj 中建立一个django项目
  2. 使用 apache wsgi 方式提供web服务
  3. 通过 http://firstdj/ 访问hello页面

准备:安装需要的软件

      这个比较简单,没什么特别注意的。

 # 安装 apache2

$ sudo apt-get -y install apache2-mpm-worker apache2-dev

 # 安装 python

$ sudo apt-get -y install python python-dev python-setuptools

 # 安装 python 的辅助软件

$ sudo easy_install virtualenv virtualenvwrapper pip

实验一、使用apache2提供静态页面

目的:

  1. 验证 apache2的安装
  2. 配置虚拟主机

apache 预备知识

可执行程序 /usr/sbin/apache2

配置文件目录 /etc/apache2/

网站(web)文件目录 /var/www

这个可以配置,修改 /etc/apache2/sites-available/default 这个文件的下面的字段 DocumentRoot /var/www ,比如你改到/var/temp 那么就把这行改成:

DocumentRoot /var/temp

配置文件并不是在httpd.conf里面,而是apache2.conf,而这里面并没有配置所有的东西,如端口是在ports.conf这个文件里面,而网站的根目录是在

/etc/apache2/sites-available/default

这个文件中。 虽然也有httpd.conf这个文件,但是httpd.conf里面是空的,其实你可以在这里面加一些配置,因为apache2.conf里面会把httpd.conf加到它的文件里面。

操作思路

  1. 修改主机名字为 firstdj ,作为域名
  2. 禁用系统默认的 default 虚拟站点
  3. 建立一个最简化的虚拟主机,使用 http://firstdj/ 访问。

具体步骤

  • 修改主机名

      通过修改/etc/hostname把主机名改为 firstdj ,为了清晰,进入root账户)。

            $ sudo su
            # echo "firstdj" > /etc/hostname
            # echo -e "\n127.0.0.1 firstdj.local firstdj\n" >> /etc/hosts
            # hostname -F /etc/hostname

      默认这个时候已经能够在 http://firstdj/ 访问了。如果你能够看到 It works! 页面,说明 apache2 安装正常。否则检查 apache2 是否在运行:

            $ sudo su
            # service apache2 status      # 查看状态
            # service apache2 start       # 启动
            # service apache2 stop        # 停止
            # service apache2 reload      # 重新应用配置文件
            # service apache2 restart     # 重新启动进程
  • 配置虚拟主机

      虽然这时候能够访问 http://firstdj/ ,但实际上是ubuntu系统本身安装后给的默认配置

            $ cd /etc/apache2                  # 进入 apache2 的配置目录
            $ ls ./sites-enabled               # 查看当前生效的站点
                    返回 000-default , 这是ubuntu默认启动的站点

            $ sudo su
            # a2dissite default                # 取消默认站点 default 
                    这时候sites-enabled目录下没有文件
            # service apache2 reload           # 使配置生效

      现在刷新一下 http://firstdj/ ,应该已经不能访问了。现在 /etc/apache2/sites-available/ 目录下,建立一个名为 firstdj 的文件,为了清晰,我尽量进行了删减,具体内容如下:

                <VirtualHost *:80>
                    ServerName firstdj
                    DocumentRoot /var/www
                </VirtualHost>

      配置文件建立完毕,我们让它生效。

            $ sudo su
            # a2ensite firstdj                 # 激活 firstdj 站点
            # ls /etc/apache2/sites-enabled/   # 查看当前生效的站点
                    返回 firstdj ,表示只有firstdj站点有效

            # apachectl configtest             # 检查一下 apache2 配置文件语法
                    返回结果:
                    apache2: Could not reliably determine the server's 
                             fully qualified domain name, using 
                             127.0.0.1 for ServerName
                    Syntax OK

            # echo -e "\nServerName firstdj\n" >> /etc/apache2/apache2.conf
                    在 apache2.conf 中增加主机名后解决报错问题

            # apachectl configtest             # 这次结果应该只有 Syntax OK

            # service apache2 reload

      现在又能够正常访问 http://firstdj/ 。

实验二、安装配置 wsgi 模块

操作思路

  1. 安装 wsgi 模块
  2. 配置一个简单的虚拟主机

具体步骤

  • 安装 mod_wsgi

      我为了省事,采用源安装,如果需要3.4版本,可以采用源码安装,参考这里。

            $ sudo apt-get install libapache2-mod-wsgi   #安装 mod_wsgi

            $ sudo dpkg -l libapache2-mod-wsgi           #查看wsgi的版本
                   结果: libapache2-mod 3.3-4build1

            $ a2enmod wsgi                               #验证模块安装正常 
                    Module wsgi already enabled
  • 验证 wsgi

      为了验证wsgi的正常使用,准备手工建一个最简单的wsgi应用,实际就是一个py脚本。

  1. 在 /var/www/目录下,建立一个名为 main.wsgi 文件,内容如下:

       def application(environ, start_response):  
            status = '200 OK'  
            output = 'Hello World!\n试试中文'  
            response_headers = [('Content-type', 'text/plain'),  
                ('Content-Length', str(len(output)))]  
            start_response(status, response_headers)  
            return [output]
    
  2. 在 /etc/apache2/sites-available/firstdj 中增加一行,同时可以取消 DocumentRoot 配置,修改后内容如下:

       <VirtualHost *:80>
            ServerName firstdj
    
            WSGIScriptAlias / /var/www/main.wsgi
    
       </VirtualHost>
    
  3. 应用配置

            $ sudo service apache2 reload

现在刷新 http://firstdj 能够返回

Hello World!

说明 wsgi 解析正常

实验三、直接安装django

      在实际生产环境,通常会使用 virtualenv 来支持多版本的python应用,但是同样也增了 wsgi 的配置复杂性,所以先进行最简单的试验。

目的:

  1. 在本机安装 django
  2. 配置 apache + wsgi

操作思路

  1. 在系统范围安装 django (不使用 VirtualEnv)
  2. 使用 wsgi 解析 django
  3. 跑通 django book 的 helloworld 例子.

具体步骤

  • 安装 django
            $ sudo pip install django

系统默认会把 django 安装到 /usr/local/lib/python2.7/dist-packages 目录中

  • 在 ~/目录建立一个 django 项目
            $ cd ~                                  # 进入home目录
            $ django-admin.py startproject firstdj  # 建立一个 firstdj 项目
            $ cd ~/firstdj
            $ python manage.py runserver            # 启动django测试服务器

访问 http://127.0.0.1:8000/ ,能够看到 django 的 It Worked! 页面,说明django安装正常。

  • 配置 wsgi 解析 django
         1. 修改 django 项目的 ~/firstdj/firstdj/wsgi.py 文件

去掉注释后,默认的 wsgi.py 文件内容为:

                import os

                os.environ.setdefault("DJANGO_SETTINGS_MODULE", "firstdj.settings")
                from django.core.wsgi import get_wsgi_application
                application = get_wsgi_application()

增加 firstdj 项目的路径到系统路径,修改后完整的 wsgi.py 文件内容如下:

                import os

                import sys
                root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
                sys.path.insert(0, os.path.abspath(os.path.join(root_path, 'firstdj')))
                sys.path.insert(0, root_path)

                os.environ.setdefault("DJANGO_SETTINGS_MODULE", "firstdj.settings")
                from django.core.wsgi import get_wsgi_application
                application = get_wsgi_application()

         2. 修改 apache2 的配置文件 /etc/apache2/sites-available/firstdj

更换文件中的 main.wsgi 为刚才修改的 wsgi.py , 修改后的内容是:

                <VirtualHost *:80>
                    ServerName firstdj
                    WSGIScriptAlias / /home/bl/firstdj/firstdj/wsgi.py
                </VirtualHost>

         3. 重新应用 apache2 配置文件

                 $ sudo service apache2 reload

访问 http://firstdj/ ,能够看到 django 的 It Worked! 页面,说明django安装正常。

        1. 新建 ~/firstdj/firstdj/views.py 文件,内容如下:

            # -*- coding: UTF-8 -*-
            from django.http import HttpResponse

            def hello(request):
                return HttpResponse("This is django Hello World")

        2. 修改 ~/firstdj/firstdj/urls.py 文件,增加 hello的映射,去掉注释后内容如下:

            from django.conf.urls import patterns, include, url

            urlpatterns = patterns('',

                url(r'^$', 'firstdj.views.hello'),

            )

        3. 验证 hello world 正常

            $ cd ~/firstdj/
            $ python manage.py runserver

访问 http://127.0.0.1:8000/ ,能够看到 This is django Hello World 页面,说明 hello 配置正常。

        4. 重新应用 apache2 配置文件

            $ sudo service apache2 reload

访问 http://firstdj/ ,能够看到 django 的 This is django Hello World 页面,说明django 被 wsgi 正常解析了。

实验四、通过 virtualenv 使用 django

      在刚才成功的基础上,使用 virtualenv 的方式使用 django,核心的问题是修改 ~/firstdj/firstdj/wsgi.py 文件,指定正确的。

目的:

  1. 配置 virtualenv 环境下的 django + apache + wsgi
  2. virtualenvwrapper 方式下的配置

操作思路

  1. 删除系统级的 django
  2. 在 ~/firstdj/ 目录下,配置 virtualenv
  3. 使 http://firstdj/ 生效
  4. 使用 virtualenvwrapper 方式

具体步骤

  • 删除系统 django
            $ sudo pip uninstall django
  • 在 ~/firstdj/ 目录下建立 venv 环境
            $ cd ~/firstdj/
            $ virtualenv venv

现在 ~/firstdj/ 目录下的结构是:

    /home/bl/firstdj
        |---venv
        |    |---local
        |    |---include
        |    |---lib
        |    |    |---python2.7
        |    |    |        |---site-packages
        |    |    |        |            |---pip-1.3.1-py2.7.egg
        |    |    |        |            |                  |---EGG-INFO
        |    |    |        |            |                  |---pip
        |    |    |        |            |                  |    |---commands
        |    |    |        |            |                  |    |---backwardcompat
        |    |    |        |            |                  |    |---vcs
        |    |    |        |---distutils
        |    |---bin
        |---firstdj
  • 在新建的 venv 环境下安装 django
            $ cd ~/firstdj/
            $ ~/firstdj/venv/bin/pip install django
  • 把新建的 venv 环境下的python 包路径(~/firstdj/venv/lib/python2.7/site-packages/) 加入系统路径中。
         1. 在 ~/firstdj/firstdj/wsgi.py 文件中增加一行,修改后内容如下:

            import os
            import sys

            root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
            sys.path.insert(0, os.path.abspath(os.path.join(root_path, 'firstdj')))
            sys.path.insert(0, root_path)

            sys.path.insert(0, os.path.abspath(os.path.join(root_path, 'venv/lib/python2.7/site-packages/')))

            os.environ.setdefault("DJANGO_SETTINGS_MODULE", "firstdj.settings")
            from django.core.wsgi import get_wsgi_application
            application = get_wsgi_application()

        2. 重新应用 apache2 配置

            $ sudo service apache2 reload

现在访问 http://firstdj/ ,又能够看到 django 的 This is django Hello World 页面。

  • 最后一步就是在 virtualenvwrapper 环境下配置 wsgi , 和普通 virtualenv 的环境的唯一不同是virtualenvwrapper 的python 安装包路径默认在 ~/.virtualenvs 目录下,比如以环境名 ELC 为例,它的安装包路径是:
            /.virtualenvs/ELC/lib/python2.7/site-packages
  • 相应的修改 ~/firstdj/firstdj/wsgi.py 文件,修改后内容如下:
            import os
            import sys

            root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
            sys.path.insert(0, os.path.abspath(os.path.join(root_path, 'firstdj')))
            sys.path.insert(0, root_path)

            sys.path.insert(0, '/home/bl/.virtualenvs/ELC/lib/python2.7/site-packages/')

            os.environ.setdefault("DJANGO_SETTINGS_MODULE", "firstdj.settings")
            from django.core.wsgi import get_wsgi_application
            application = get_wsgi_application()

      再次重新应用 apache2 配置后,访问 http://firstdj/ ,又能够看到 django 的 This is django Hello World 页面。

  • 增加django的静态链接

      为了能够访问 django 的静态文件,比如各种模版,还需要在 /etc/apache2/sites-available/firstdj 中设置一些别名,最终完整的 apache2 虚拟站点通常是这个样子:

        <VirtualHost *:80>
            ServerAdmin root@firstdj
            ServerName firstdj

            Alias /site_media/ /home/bl/firstdj/site_media/
            Alias /robots.txt /home/bl/firstdj/site_media/robots.txt
            Alias /favicon.ico /home/bl/firstdj/site_media/favicon.ico
            Alias /static/ /home/bl/.virtualenvs/ELC/lib/python2.7/site-packages/django/contrib/admin/static/

            CustomLog "|/usr/sbin/rotatelogs /home/bl/firstdj/logs/access.log.%Y%m%d-%H%M%S 5M" combined
            ErrorLog "|/usr/sbin/rotatelogs /home/bl/firstdj/logs/error.log.%Y%m%d-%H%M%S 5M"
            LogLevel warn

            WSGIDaemonProcess firstdj user=bl group=bl processes=1 threads=15 maximum-requests=10000 python-path=/home/bl/.virtualenvs/ELC/lib/python2.7/site-packages/ 
            WSGIProcessGroup firstdj
            WSGIScriptAlias / /home/bl/firstdj/firstdj/wsgi.py

            <Directory /home/bl/firstdj/firstdj/site_media>
                Order deny,allow
                Allow from all
                Options -Indexes FollowSymLinks
            </Directory>

        </VirtualHost>

抱歉!评论已关闭.