一般来说在生产环境部署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自带的服务器会报错