Django程序自带了自己的服务器程序(manage.py程序),即运行python manage.py runserver就打开了Django自带的服务器程序。Django自带的服务器程序功能太弱,一般只在开发过程中使用。程序开发完后,一般使用apache或其他软件来运行Django程序而不用Django自带的服务器程序。
将Django程序部署到Apache服务器下的配置过程如下:
1、下载mod_wsgi模块,并将其放到apache的模块目录下
下载地址:mod_wsgi文件后将其重命名为mod_wsgi.so,然后放到Apache的module目录下。
2、打开apache配置文件httpd.conf,修改如下:
(1)添加Listen端口
默认是80端口,如果apache服务器下还有其他网站,为了不影响原有的网站,换用其他端口,如8001端口。
则添加 Listen 8001
(2)为apache加载wsgi模块
即在配置文件的模块列表下面添加
LoadModule wsgi_module modules/mod_wsgi.so
(3)与Django项目映射(重要)
在httpd.conf中添加与Django对应的目录映射何配置,如:
<VirtualHost *:8001> ServerName localhost ServerAlias 127.0.0.1 DocumentRoot F:/code/django/relation WSGIScriptAlias / F:/code/django/relation/wsgi/relation.wsgi Alias /static F:/code/django/relation/static <Location "/static"> SetHandler None </Location> <Directory "F:/code/django/relation/static"> Order Deny,Allow Allow from all </Directory> <Directory "F:/code/django/relation/wsgi"> Order Deny,Allow Allow from all </Directory> </VirtualHost>
说明:8001就是上面设置的监听端口;DocumentRoot参数是Django项目所在的目录;WSGIScriptAlias后面有一个 /千万别漏了,文件F:/code/django/relation/wsgi/relation.wsgi现在还不存在,等下一步配置中建立。Alias对应的是虚拟路径,虚拟路径一般用于存放Django项目的css、jpg等静态资源。访问虚拟路径不受Django中的urls.py中url的影响,当访问虚拟路径时会到后面配置的物理路径中去请求资源。如上面的配置生效后,访问http://127.0.0.1:8001/static/xxx时访问的是 F:/code/django/relation/static目录中的文件,不受Django的url设置限制。下面的几项设置是设置路径的访问权限的,照着设置即可。
(4)创建wsgi文件
在项目目录下创建wsgi目录,在其中新建文件”项目名称.wsgi”,如我的是relation.wsgi,当然也可以选择其他的名称只要和第(3)步配置文件保持一致即可。文件内容如下:
# complete_project.wsgi is configured to live in projects/complete_project/deploy. # If you move this file you need to reconfigure the paths below. import os import sys # redirect sys.stdout to sys.stderr for bad libraries like geopy that uses # print statements for optional import exceptions. sys.stdout = sys.stderr from os.path import abspath, dirname, join from site import addsitedir from django.core.handlers.wsgi import WSGIHandler sys.path.insert(0, abspath(join(dirname(__file__), "../"))) sys.path.insert(0, abspath(join(dirname(__file__), ". . /. . /"))) os.environ["DJANGO_SETTINGS_MODULE"] = "relation.settings" application = WSGIHandler()
上面几步设置后,重启apache服务器后,就可以通过apache访问Django项目了。
参考文献:
1、Apache+Django性能优化之mod_wsgi篇 http://www.cnblogs.com/zhengyun_ustc/archive/2009/08/11/wsgi.html
2、在Windows上搭建Django+python+apache+wsgi http://blog.sina.com.cn/s/blog_6c739e630101eqrg.html