2005-07-18 23:25:58 +08:00
|
|
|
"""
|
2011-05-29 05:28:52 +08:00
|
|
|
HTTP server that implements the Python WSGI protocol (PEP 333, rev 1.21).
|
2005-07-18 23:25:58 +08:00
|
|
|
|
2011-05-29 05:28:52 +08:00
|
|
|
Based on wsgiref.simple_server which is part of the standard library since 2.5.
|
2005-07-18 23:25:58 +08:00
|
|
|
|
|
|
|
This is a simple server for use in testing or debugging Django apps. It hasn't
|
2011-05-29 05:28:52 +08:00
|
|
|
been reviewed for security issues. DON'T USE IT FOR PRODUCTION USE!
|
2005-07-18 23:25:58 +08:00
|
|
|
"""
|
|
|
|
|
2007-07-16 11:50:22 +08:00
|
|
|
import os
|
2010-11-26 21:33:53 +08:00
|
|
|
import socket
|
2007-07-16 11:50:22 +08:00
|
|
|
import sys
|
2011-05-29 05:28:52 +08:00
|
|
|
import traceback
|
2007-07-16 11:50:22 +08:00
|
|
|
import urllib
|
2011-06-30 17:06:19 +08:00
|
|
|
import urlparse
|
2011-06-17 21:08:36 +08:00
|
|
|
from SocketServer import ThreadingMixIn
|
2011-05-29 05:28:52 +08:00
|
|
|
from wsgiref import simple_server
|
|
|
|
from wsgiref.util import FileWrapper # for backwards compatibility
|
2005-07-18 23:25:58 +08:00
|
|
|
|
2011-05-29 05:28:52 +08:00
|
|
|
import django
|
2011-10-22 12:30:10 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2010-01-04 20:16:09 +08:00
|
|
|
from django.core.management.color import color_style
|
2011-10-22 12:30:10 +08:00
|
|
|
from django.core.wsgi import get_wsgi_application
|
|
|
|
from django.utils.importlib import import_module
|
2007-10-31 11:59:40 +08:00
|
|
|
|
2011-05-29 05:28:52 +08:00
|
|
|
__all__ = ['WSGIServer', 'WSGIRequestHandler']
|
2005-07-18 23:25:58 +08:00
|
|
|
|
|
|
|
|
2011-10-22 12:30:10 +08:00
|
|
|
def get_internal_wsgi_application():
|
|
|
|
"""
|
|
|
|
Loads and returns the WSGI application as configured by the user in
|
|
|
|
``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
|
|
|
|
this will be the ``application`` object in ``projectname/wsgi.py``.
|
|
|
|
|
|
|
|
This function, and the ``WSGI_APPLICATION`` setting itself, are only useful
|
|
|
|
for Django's internal servers (runserver, runfcgi); external WSGI servers
|
|
|
|
should just be configured to point to the correct application object
|
|
|
|
directly.
|
|
|
|
|
|
|
|
If settings.WSGI_APPLICATION is not set (is ``None``), we just return
|
|
|
|
whatever ``django.core.wsgi.get_wsgi_application`` returns.
|
|
|
|
|
|
|
|
"""
|
|
|
|
from django.conf import settings
|
|
|
|
app_path = getattr(settings, 'WSGI_APPLICATION')
|
|
|
|
if app_path is None:
|
|
|
|
return get_wsgi_application()
|
|
|
|
module_name, attr = app_path.rsplit('.', 1)
|
|
|
|
try:
|
|
|
|
mod = import_module(module_name)
|
2012-04-29 00:09:37 +08:00
|
|
|
except ImportError as e:
|
2011-10-22 12:30:10 +08:00
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"WSGI application '%s' could not be loaded; "
|
|
|
|
"could not import module '%s': %s" % (app_path, module_name, e))
|
|
|
|
try:
|
|
|
|
app = getattr(mod, attr)
|
2012-04-29 00:09:37 +08:00
|
|
|
except AttributeError as e:
|
2011-10-22 12:30:10 +08:00
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"WSGI application '%s' could not be loaded; "
|
|
|
|
"can't find '%s' in module '%s': %s"
|
|
|
|
% (app_path, attr, module_name, e))
|
|
|
|
|
|
|
|
return app
|
|
|
|
|
|
|
|
|
2005-07-18 23:25:58 +08:00
|
|
|
class WSGIServerException(Exception):
|
|
|
|
pass
|
|
|
|
|
2011-03-02 18:40:48 +08:00
|
|
|
|
2011-05-29 05:28:52 +08:00
|
|
|
class ServerHandler(simple_server.ServerHandler, object):
|
2006-05-02 09:31:56 +08:00
|
|
|
error_status = "500 INTERNAL SERVER ERROR"
|
2005-07-18 23:25:58 +08:00
|
|
|
|
2007-06-22 15:15:04 +08:00
|
|
|
def write(self, data):
|
2005-07-18 23:25:58 +08:00
|
|
|
"""'write()' callable as specified by PEP 333"""
|
|
|
|
|
2007-12-01 02:28:19 +08:00
|
|
|
assert isinstance(data, str), "write() argument must be string"
|
2005-07-18 23:25:58 +08:00
|
|
|
|
|
|
|
if not self.status:
|
2006-05-02 09:31:56 +08:00
|
|
|
raise AssertionError("write() before start_response()")
|
2005-07-18 23:25:58 +08:00
|
|
|
|
|
|
|
elif not self.headers_sent:
|
|
|
|
# Before the first output, send the stored headers
|
|
|
|
self.bytes_sent = len(data) # make sure we know content-length
|
|
|
|
self.send_headers()
|
|
|
|
else:
|
|
|
|
self.bytes_sent += len(data)
|
|
|
|
|
|
|
|
# XXX check Content-Length and truncate if too many bytes written?
|
2007-12-17 19:46:48 +08:00
|
|
|
|
|
|
|
# If data is too large, socket will choke, so write chunks no larger
|
|
|
|
# than 32MB at a time.
|
|
|
|
length = len(data)
|
|
|
|
if length > 33554432:
|
|
|
|
offset = 0
|
|
|
|
while offset < length:
|
|
|
|
chunk_size = min(33554432, length)
|
|
|
|
self._write(data[offset:offset+chunk_size])
|
|
|
|
self._flush()
|
|
|
|
offset += chunk_size
|
|
|
|
else:
|
|
|
|
self._write(data)
|
|
|
|
self._flush()
|
2005-07-18 23:25:58 +08:00
|
|
|
|
|
|
|
def error_output(self, environ, start_response):
|
2011-05-29 05:28:52 +08:00
|
|
|
super(ServerHandler, self).error_output(environ, start_response)
|
2005-07-18 23:25:58 +08:00
|
|
|
return ['\n'.join(traceback.format_exception(*sys.exc_info()))]
|
|
|
|
|
|
|
|
|
2011-05-29 05:28:52 +08:00
|
|
|
class WSGIServer(simple_server.WSGIServer, object):
|
2005-07-18 23:25:58 +08:00
|
|
|
"""BaseHTTPServer that implements the Python WSGI protocol"""
|
|
|
|
|
2010-11-26 21:33:53 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
if kwargs.pop('ipv6', False):
|
|
|
|
self.address_family = socket.AF_INET6
|
2011-05-29 05:28:52 +08:00
|
|
|
super(WSGIServer, self).__init__(*args, **kwargs)
|
2010-11-26 21:33:53 +08:00
|
|
|
|
2005-07-18 23:25:58 +08:00
|
|
|
def server_bind(self):
|
|
|
|
"""Override server_bind to store the server name."""
|
|
|
|
try:
|
2011-05-29 05:28:52 +08:00
|
|
|
super(WSGIServer, self).server_bind()
|
2012-04-29 00:09:37 +08:00
|
|
|
except Exception as e:
|
2010-01-11 02:36:20 +08:00
|
|
|
raise WSGIServerException(e)
|
2005-07-18 23:25:58 +08:00
|
|
|
self.setup_environ()
|
|
|
|
|
|
|
|
|
2011-05-29 05:28:52 +08:00
|
|
|
class WSGIRequestHandler(simple_server.WSGIRequestHandler, object):
|
2005-07-27 01:49:49 +08:00
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.conf import settings
|
2012-04-09 05:13:32 +08:00
|
|
|
self.admin_static_prefix = urlparse.urljoin(settings.STATIC_URL, 'admin/')
|
2008-06-30 19:32:50 +08:00
|
|
|
# We set self.path to avoid crashes in log_message() on unsupported
|
|
|
|
# requests (like "OPTIONS").
|
|
|
|
self.path = ''
|
2010-01-04 20:16:09 +08:00
|
|
|
self.style = color_style()
|
2011-05-29 05:28:52 +08:00
|
|
|
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
|
2005-07-27 01:49:49 +08:00
|
|
|
|
2005-07-18 23:25:58 +08:00
|
|
|
def get_environ(self):
|
|
|
|
env = self.server.base_environ.copy()
|
|
|
|
env['SERVER_PROTOCOL'] = self.request_version
|
|
|
|
env['REQUEST_METHOD'] = self.command
|
|
|
|
if '?' in self.path:
|
|
|
|
path,query = self.path.split('?',1)
|
|
|
|
else:
|
|
|
|
path,query = self.path,''
|
|
|
|
|
|
|
|
env['PATH_INFO'] = urllib.unquote(path)
|
|
|
|
env['QUERY_STRING'] = query
|
|
|
|
env['REMOTE_ADDR'] = self.client_address[0]
|
2012-05-17 19:39:00 +08:00
|
|
|
env['CONTENT_TYPE'] = self.headers.get('content-type', 'text/plain')
|
2005-07-18 23:25:58 +08:00
|
|
|
|
2012-05-17 19:39:00 +08:00
|
|
|
length = self.headers.get('content-length')
|
2005-07-18 23:25:58 +08:00
|
|
|
if length:
|
|
|
|
env['CONTENT_LENGTH'] = length
|
|
|
|
|
2012-05-17 19:39:00 +08:00
|
|
|
for key, value in self.headers.items():
|
|
|
|
key = key.replace('-','_').upper()
|
|
|
|
value = value.strip()
|
|
|
|
if key in env:
|
|
|
|
# Skip content length, type, etc.
|
|
|
|
continue
|
|
|
|
if 'HTTP_' + key in env:
|
|
|
|
# Comma-separate multiple headers
|
|
|
|
env['HTTP_' + key] += ',' + value
|
2005-07-18 23:25:58 +08:00
|
|
|
else:
|
2012-05-17 19:39:00 +08:00
|
|
|
env['HTTP_' + key] = value
|
2005-07-18 23:25:58 +08:00
|
|
|
return env
|
|
|
|
|
2005-07-27 01:49:49 +08:00
|
|
|
def log_message(self, format, *args):
|
|
|
|
# Don't bother logging requests for admin images or the favicon.
|
2012-04-09 05:13:32 +08:00
|
|
|
if (self.path.startswith(self.admin_static_prefix)
|
2011-05-29 05:28:52 +08:00
|
|
|
or self.path == '/favicon.ico'):
|
2005-07-27 01:49:49 +08:00
|
|
|
return
|
2010-01-04 20:16:09 +08:00
|
|
|
|
|
|
|
msg = "[%s] %s\n" % (self.log_date_time_string(), format % args)
|
|
|
|
|
|
|
|
# Utilize terminal colors, if available
|
|
|
|
if args[1][0] == '2':
|
|
|
|
# Put 2XX first, since it should be the common case
|
|
|
|
msg = self.style.HTTP_SUCCESS(msg)
|
|
|
|
elif args[1][0] == '1':
|
|
|
|
msg = self.style.HTTP_INFO(msg)
|
2010-01-24 01:26:56 +08:00
|
|
|
elif args[1] == '304':
|
|
|
|
msg = self.style.HTTP_NOT_MODIFIED(msg)
|
2010-01-04 20:16:09 +08:00
|
|
|
elif args[1][0] == '3':
|
|
|
|
msg = self.style.HTTP_REDIRECT(msg)
|
|
|
|
elif args[1] == '404':
|
|
|
|
msg = self.style.HTTP_NOT_FOUND(msg)
|
|
|
|
elif args[1][0] == '4':
|
|
|
|
msg = self.style.HTTP_BAD_REQUEST(msg)
|
|
|
|
else:
|
|
|
|
# Any 5XX, or any other response
|
|
|
|
msg = self.style.HTTP_SERVER_ERROR(msg)
|
|
|
|
|
|
|
|
sys.stderr.write(msg)
|
2005-07-27 01:49:49 +08:00
|
|
|
|
2010-10-20 09:33:24 +08:00
|
|
|
|
2011-06-17 21:08:36 +08:00
|
|
|
def run(addr, port, wsgi_handler, ipv6=False, threading=False):
|
2005-08-20 05:23:56 +08:00
|
|
|
server_address = (addr, port)
|
2011-06-17 21:08:36 +08:00
|
|
|
if threading:
|
|
|
|
httpd_cls = type('WSGIServer', (ThreadingMixIn, WSGIServer), {})
|
|
|
|
else:
|
|
|
|
httpd_cls = WSGIServer
|
|
|
|
httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
|
2005-07-18 23:25:58 +08:00
|
|
|
httpd.set_app(wsgi_handler)
|
|
|
|
httpd.serve_forever()
|