使用CGI+apache部署django应用

一般来说在生产环境部署django应用都需要服务器支持WSGI,但是由于我司服务器系统过于老旧,无法安装WSGI相关的模块,所以只好退而求其次,使用CGI方式来部署django应用,注意这种方式应当仅仅作为一种备选部署方式,只适用于公司内网或者访问量很少的情况,正常情况下还是建议升级服务器并安装相关模块来解决类似问题。

将django自动生成的wsgi.py文件修改为以下内容即可:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_site.settings')

import sys
sys.path.append(os.path.abspath(__file__))
from django.core.wsgi import get_wsgi_application

def run_with_cgi(application):
     environ = dict(os.environ.items())
     environ['wsgi.input'] = sys.stdin
     environ['wsgi.errors'] = sys.stderr
     environ['wsgi.version'] = (1,0)
     environ['wsgi.multithread'] = False
     environ['wsgi.multiprocess'] = True
     environ['wsgi.run_once'] = True

     if environ.get('HTTPS','off') in ('on','1'):
         environ['wsgi.url_scheme'] = 'https'
     else:
         environ['wsgi.url_scheme'] = 'http'

     headers_set = []
     headers_sent = []

     def write(data):
         if not headers_set:
              raise AssertionError("write() before start_response()")
         elif not headers_sent:
              # Before the first output, send the stored headers
              status, response_headers = headers_sent[:] = headers_set
              for header in response_headers:
                  sys.stdout.write('%s: %s\r\n' % header)
              sys.stdout.write('Content-Length: %s\r\n\r\n' % len(data))

         sys.stdout.write(data)
         sys.stdout.flush()

     def start_response(status,response_headers,exc_info=None):
         if exc_info:
             try:
                 if headers_sent:
                     # Re-raise original exception if headers sent
                     raise exc_info[0], exc_info[1], exc_info[2]
             finally:
                 exc_info = None # avoid dangling circular ref
         elif headers_set:
             raise AssertionError("Headers already set!")

         headers_set[:] = [status,response_headers]
         return write

     result = application(environ, start_response)
     try:
         for data in result:
             if data: # don't send headers until body appears
                 write(data)
         if not headers_sent:
             write('') # send headers now if body was empty
     finally:
         if hasattr(result,'close'):
             result.close()
  run_with_cgi(get_wsgi_application())
  # application = get_wsgi_application()

注意如果使用python manage.py runserver进行测试时应注释掉run_with_cgi(get_wsgi_application())并反注释最后一行,否则django自带的服务器会报错

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值