Jason R. Coombs avatar Jason R. Coombs committed 9c2d91c

Resave wsgiserver modules with extra whitespace removed (will make subsequent changesets easier to read).

Comments (0)

Files changed (2)

cherrypy/wsgiserver/wsgiserver2.py

 (without using CherryPy's application machinery)::
 
     from cherrypy import wsgiserver
-    
+
     def my_crazy_app(environ, start_response):
         status = '200 OK'
         response_headers = [('Content-type','text/plain')]
         start_response(status, response_headers)
         return ['Hello world!']
-    
+
     server = wsgiserver.CherryPyWSGIServer(
                 ('0.0.0.0', 8070), my_crazy_app,
                 server_name='www.cherrypy.example')
     server.start()
-    
-The CherryPy WSGI server can serve as many WSGI applications 
+
+The CherryPy WSGI server can serve as many WSGI applications
 as you want in one instance by using a WSGIPathInfoDispatcher::
-    
+
     d = WSGIPathInfoDispatcher({'/': my_crazy_app, '/blog': my_blog_app})
     server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 80), d)
-    
+
 Want SSL support? Just set server.ssl_adapter to an SSLAdapter instance.
 
 This won't call the CherryPy engine (application side) at all, only the
 
 def plat_specific_errors(*errnames):
     """Return error numbers for all errors in errnames on this platform.
-    
+
     The 'errno' module contains different global constants depending on
     the specific platform (OS). This function will return the list of
     numeric values for a given list of potential names.
 
 def read_headers(rfile, hdict=None):
     """Read headers from the given stream into the given header dict.
-    
+
     If hdict is None, a new header dict is created. Returns the populated
     header dict.
-    
+
     Headers which are repeated are folded together using a comma if their
     specification so dictates.
-    
+
     This function raises ValueError when the read bytes violate the HTTP spec.
     You should probably return "400 Bad Request" if this happens.
     """
     if hdict is None:
         hdict = {}
-    
+
     while True:
         line = rfile.readline()
         if not line:
             # No more data--illegal end of headers
             raise ValueError("Illegal end of headers.")
-        
+
         if line == CRLF:
             # Normal end of headers
             break
         if not line.endswith(CRLF):
             raise ValueError("HTTP requires CRLF terminators")
-        
+
         if line[0] in (SPACE, TAB):
             # It's a continuation line.
             v = line.strip()
             k = k.strip().title()
             v = v.strip()
             hname = k
-        
+
         if k in comma_separated_headers:
             existing = hdict.get(hname)
             if existing:
                 v = ", ".join((existing, v))
         hdict[hname] = v
-    
+
     return hdict
 
 
 
 class SizeCheckWrapper(object):
     """Wraps a file-like object, raising MaxSizeExceeded if too large."""
-    
+
     def __init__(self, rfile, maxlen):
         self.rfile = rfile
         self.maxlen = maxlen
         self.bytes_read = 0
-    
+
     def _check_length(self):
         if self.maxlen and self.bytes_read > self.maxlen:
             raise MaxSizeExceeded()
-    
+
     def read(self, size=None):
         data = self.rfile.read(size)
         self.bytes_read += len(data)
         self._check_length()
         return data
-    
+
     def readline(self, size=None):
         if size is not None:
             data = self.rfile.readline(size)
             self.bytes_read += len(data)
             self._check_length()
             return data
-        
+
         # User didn't specify a size ...
         # We read the line in chunks to make sure it's not a 100MB line !
         res = []
             # See http://www.cherrypy.org/ticket/421
             if len(data) < 256 or data[-1:] == "\n":
                 return EMPTY.join(res)
-    
+
     def readlines(self, sizehint=0):
         # Shamelessly stolen from StringIO
         total = 0
                 break
             line = self.readline()
         return lines
-    
+
     def close(self):
         self.rfile.close()
-    
+
     def __iter__(self):
         return self
-    
+
     def __next__(self):
         data = next(self.rfile)
         self.bytes_read += len(data)
         self._check_length()
         return data
-    
+
     def next(self):
         data = self.rfile.next()
         self.bytes_read += len(data)
 
 class KnownLengthRFile(object):
     """Wraps a file-like object, returning an empty string when exhausted."""
-    
+
     def __init__(self, rfile, content_length):
         self.rfile = rfile
         self.remaining = content_length
-    
+
     def read(self, size=None):
         if self.remaining == 0:
             return ''
             size = self.remaining
         else:
             size = min(size, self.remaining)
-        
+
         data = self.rfile.read(size)
         self.remaining -= len(data)
         return data
-    
+
     def readline(self, size=None):
         if self.remaining == 0:
             return ''
             size = self.remaining
         else:
             size = min(size, self.remaining)
-        
+
         data = self.rfile.readline(size)
         self.remaining -= len(data)
         return data
-    
+
     def readlines(self, sizehint=0):
         # Shamelessly stolen from StringIO
         total = 0
                 break
             line = self.readline(sizehint)
         return lines
-    
+
     def close(self):
         self.rfile.close()
-    
+
     def __iter__(self):
         return self
-    
+
     def __next__(self):
         data = next(self.rfile)
         self.remaining -= len(data)
 
 class ChunkedRFile(object):
     """Wraps a file-like object, returning an empty string when exhausted.
-    
+
     This class is intended to provide a conforming wsgi.input value for
     request entities that have been encoded with the 'chunked' transfer
     encoding.
     """
-    
+
     def __init__(self, rfile, maxlen, bufsize=8192):
         self.rfile = rfile
         self.maxlen = maxlen
         self.buffer = EMPTY
         self.bufsize = bufsize
         self.closed = False
-    
+
     def _fetch(self):
         if self.closed:
             return
-        
+
         line = self.rfile.readline()
         self.bytes_read += len(line)
-        
+
         if self.maxlen and self.bytes_read > self.maxlen:
             raise MaxSizeExceeded("Request Entity Too Large", self.maxlen)
-        
+
         line = line.strip().split(SEMICOLON, 1)
-        
+
         try:
             chunk_size = line.pop(0)
             chunk_size = int(chunk_size, 16)
         except ValueError:
             raise ValueError("Bad chunked transfer size: " + repr(chunk_size))
-        
+
         if chunk_size <= 0:
             self.closed = True
             return
-        
+
 ##            if line: chunk_extension = line[0]
-        
+
         if self.maxlen and self.bytes_read + chunk_size > self.maxlen:
             raise IOError("Request Entity Too Large")
-        
+
         chunk = self.rfile.read(chunk_size)
         self.bytes_read += len(chunk)
         self.buffer += chunk
-        
+
         crlf = self.rfile.read(2)
         if crlf != CRLF:
             raise ValueError(
                  "Bad chunked transfer coding (expected '\\r\\n', "
                  "got " + repr(crlf) + ")")
-    
+
     def read(self, size=None):
         data = EMPTY
         while True:
             if size and len(data) >= size:
                 return data
-            
+
             if not self.buffer:
                 self._fetch()
                 if not self.buffer:
                     # EOF
                     return data
-            
+
             if size:
                 remaining = size - len(data)
                 data += self.buffer[:remaining]
                 self.buffer = self.buffer[remaining:]
             else:
                 data += self.buffer
-    
+
     def readline(self, size=None):
         data = EMPTY
         while True:
             if size and len(data) >= size:
                 return data
-            
+
             if not self.buffer:
                 self._fetch()
                 if not self.buffer:
                     # EOF
                     return data
-            
+
             newline_pos = self.buffer.find(LF)
             if size:
                 if newline_pos == -1:
                 else:
                     data += self.buffer[:newline_pos]
                     self.buffer = self.buffer[newline_pos:]
-    
+
     def readlines(self, sizehint=0):
         # Shamelessly stolen from StringIO
         total = 0
                 break
             line = self.readline(sizehint)
         return lines
-    
+
     def read_trailer_lines(self):
         if not self.closed:
             raise ValueError(
                 "Cannot read trailers until the request body has been read.")
-        
+
         while True:
             line = self.rfile.readline()
             if not line:
                 # No more data--illegal end of headers
                 raise ValueError("Illegal end of headers.")
-            
+
             self.bytes_read += len(line)
             if self.maxlen and self.bytes_read > self.maxlen:
                 raise IOError("Request Entity Too Large")
-            
+
             if line == CRLF:
                 # Normal end of headers
                 break
             if not line.endswith(CRLF):
                 raise ValueError("HTTP requires CRLF terminators")
-            
+
             yield line
-    
+
     def close(self):
         self.rfile.close()
-    
+
     def __iter__(self):
         # Shamelessly stolen from StringIO
         total = 0
 
 class HTTPRequest(object):
     """An HTTP Request (and response).
-    
+
     A single HTTP connection may consist of multiple request/response pairs.
     """
-    
+
     server = None
     """The HTTPServer object which is receiving this request."""
-    
+
     conn = None
     """The HTTPConnection object on which this request connected."""
-    
+
     inheaders = {}
     """A dict of request headers."""
-    
+
     outheaders = []
     """A list of header tuples to write in the response."""
-    
+
     ready = False
     """When True, the request has been parsed and is ready to begin generating
     the response. When False, signals the calling Connection that the response
     should not be generated and the connection should close."""
-    
+
     close_connection = False
     """Signals the calling Connection that the request should close. This does
     not imply an error! The client and/or server may each request that the
     connection be closed."""
-    
+
     chunked_write = False
     """If True, output will be encoded with the "chunked" transfer-coding.
-    
+
     This value is set automatically inside send_headers."""
-    
+
     def __init__(self, server, conn):
         self.server= server
         self.conn = conn
-        
+
         self.ready = False
         self.started_request = False
         self.scheme = ntob("http")
         # Use the lowest-common protocol in case read_request_line errors.
         self.response_protocol = 'HTTP/1.0'
         self.inheaders = {}
-        
+
         self.status = ""
         self.outheaders = []
         self.sent_headers = False
         self.close_connection = self.__class__.close_connection
         self.chunked_read = False
         self.chunked_write = self.__class__.chunked_write
-    
+
     def parse_request(self):
         """Parse the next HTTP request start-line and message-headers."""
         self.rfile = SizeCheckWrapper(self.conn.rfile,
         else:
             if not success:
                 return
-        
+
         try:
             success = self.read_request_headers()
         except MaxSizeExceeded:
         else:
             if not success:
                 return
-        
+
         self.ready = True
-    
+
     def read_request_line(self):
         # HTTP/1.1 connections are persistent by default. If a client
         # requests a page, then idles (leaves the connection open),
         # (although your TCP stack might suffer for it: cf Apache's history
         # with FIN_WAIT_2).
         request_line = self.rfile.readline()
-        
+
         # Set started_request to True so communicate() knows to send 408
         # from here on out.
         self.started_request = True
         if not request_line:
             return False
-        
+
         if request_line == CRLF:
             # RFC 2616 sec 4.1: "...if the server is reading the protocol
             # stream at the beginning of a message and receives a CRLF
             request_line = self.rfile.readline()
             if not request_line:
                 return False
-        
+
         if not request_line.endswith(CRLF):
             self.simple_response("400 Bad Request", "HTTP requires CRLF terminators")
             return False
-        
+
         try:
             method, uri, req_protocol = request_line.strip().split(SPACE, 2)
             rp = int(req_protocol[5]), int(req_protocol[7])
         except (ValueError, IndexError):
             self.simple_response("400 Bad Request", "Malformed Request-Line")
             return False
-        
+
         self.uri = uri
         self.method = method
-        
+
         # uri may be an abs_path (including "http://host.domain.tld");
         scheme, authority, path = self.parse_request_uri(uri)
         if NUMBER_SIGN in path:
             self.simple_response("400 Bad Request",
                                  "Illegal #fragment in Request-URI.")
             return False
-        
+
         if scheme:
             self.scheme = scheme
-        
+
         qs = EMPTY
         if QUESTION_MARK in path:
             path, qs = path.split(QUESTION_MARK, 1)
-        
+
         # Unquote the path+params (e.g. "/this%20path" -> "/this path").
         # http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
         #
             return False
         path = "%2F".join(atoms)
         self.path = path
-        
+
         # Note that, like wsgiref and most other HTTP servers,
         # we "% HEX HEX"-unquote the path but not the query string.
         self.qs = qs
-        
+
         # Compare request and server HTTP protocol versions, in case our
         # server does not support the requested protocol. Limit our output
         # to min(req, server). We want the following output:
         # the client only understands 1.0. RFC 2616 10.5.6 says we should
         # only return 505 if the _major_ version is different.
         sp = int(self.server.protocol[5]), int(self.server.protocol[7])
-        
+
         if sp[0] != rp[0]:
             self.simple_response("505 HTTP Version Not Supported")
             return False
 
     def read_request_headers(self):
         """Read self.rfile into self.inheaders. Return success."""
-        
+
         # then all the http headers
         try:
             read_headers(self.rfile, self.inheaders)
             ex = sys.exc_info()[1]
             self.simple_response("400 Bad Request", ex.args[0])
             return False
-        
+
         mrbs = self.server.max_request_body_size
         if mrbs and int(self.inheaders.get("Content-Length", 0)) > mrbs:
             self.simple_response("413 Request Entity Too Large",
                 "The entity sent with the request exceeds the maximum "
                 "allowed bytes.")
             return False
-        
+
         # Persistent connection support
         if self.response_protocol == "HTTP/1.1":
             # Both server and client are HTTP/1.1
             # Either the server or client (or both) are HTTP/1.0
             if self.inheaders.get("Connection", "") != "Keep-Alive":
                 self.close_connection = True
-        
+
         # Transfer-Encoding support
         te = None
         if self.response_protocol == "HTTP/1.1":
             te = self.inheaders.get("Transfer-Encoding")
             if te:
                 te = [x.strip().lower() for x in te.split(",") if x.strip()]
-        
+
         self.chunked_read = False
-        
+
         if te:
             for enc in te:
                 if enc == "chunked":
                     self.simple_response("501 Unimplemented")
                     self.close_connection = True
                     return False
-        
+
         # From PEP 333:
         # "Servers and gateways that implement HTTP 1.1 must provide
         # transparent support for HTTP 1.1's "expect/continue" mechanism.
                 if x.args[0] not in socket_errors_to_ignore:
                     raise
         return True
-    
+
     def parse_request_uri(self, uri):
         """Parse a Request-URI into (scheme, authority, path).
-        
+
         Note that Request-URI's must be one of::
-            
+
             Request-URI    = "*" | absoluteURI | abs_path | authority
-        
+
         Therefore, a Request-URI which starts with a double forward-slash
         cannot be a "net_path"::
-        
+
             net_path      = "//" authority [ abs_path ]
-        
+
         Instead, it must be interpreted as an "abs_path" with an empty first
         path segment::
-        
+
             abs_path      = "/"  path_segments
             path_segments = segment *( "/" segment )
             segment       = *pchar *( ";" param )
         """
         if uri == ASTERISK:
             return None, None, uri
-        
+
         i = uri.find('://')
         if i > 0 and QUESTION_MARK not in uri[:i]:
             # An absoluteURI.
             authority, path = remainder.split(FORWARD_SLASH, 1)
             path = FORWARD_SLASH + path
             return scheme, authority, path
-        
+
         if uri.startswith(FORWARD_SLASH):
             # An abs_path.
             return None, None, uri
         else:
             # An authority.
             return None, uri, None
-    
+
     def respond(self):
         """Call the gateway and write its iterable output."""
         mrbs = self.server.max_request_body_size
                         "allowed bytes.")
                 return
             self.rfile = KnownLengthRFile(self.conn.rfile, cl)
-        
+
         self.server.gateway(self).respond()
-        
+
         if (self.ready and not self.sent_headers):
             self.sent_headers = True
             self.send_headers()
         if self.chunked_write:
             self.conn.wfile.sendall("0\r\n\r\n")
-    
+
     def simple_response(self, status, msg=""):
         """Write a simple response back to the client."""
         status = str(status)
                status + CRLF,
                "Content-Length: %s\r\n" % len(msg),
                "Content-Type: text/plain\r\n"]
-        
+
         if status[:3] in ("413", "414"):
             # Request Entity Too Large / Request-URI Too Long
             self.close_connection = True
                 # HTTP/1.0 had no 413/414 status nor Connection header.
                 # Emit 400 instead and trust the message body is enough.
                 status = "400 Bad Request"
-        
+
         buf.append(CRLF)
         if msg:
             if isinstance(msg, unicodestr):
                 msg = msg.encode("ISO-8859-1")
             buf.append(msg)
-        
+
         try:
             self.conn.wfile.sendall("".join(buf))
         except socket.error:
             x = sys.exc_info()[1]
             if x.args[0] not in socket_errors_to_ignore:
                 raise
-    
+
     def write(self, chunk):
         """Write unbuffered data to the client."""
         if self.chunked_write and chunk:
             self.conn.wfile.sendall(EMPTY.join(buf))
         else:
             self.conn.wfile.sendall(chunk)
-    
+
     def send_headers(self):
         """Assert, process, and send the HTTP response message-headers.
-        
+
         You must set self.status, and self.outheaders before calling this.
         """
         hkeys = [key.lower() for key, value in self.outheaders]
         status = int(self.status[:3])
-        
+
         if status == 413:
             # Request Entity Too Large. Close conn to avoid garbage.
             self.close_connection = True
                 else:
                     # Closing the conn is the only way to determine len.
                     self.close_connection = True
-        
+
         if "connection" not in hkeys:
             if self.response_protocol == 'HTTP/1.1':
                 # Both server and client are HTTP/1.1 or better
                 # Server and/or client are HTTP/1.0
                 if not self.close_connection:
                     self.outheaders.append(("Connection", "Keep-Alive"))
-        
+
         if (not self.close_connection) and (not self.chunked_read):
             # Read any remaining request body data on the socket.
             # "If an origin server receives a request that does not include an
             remaining = getattr(self.rfile, 'remaining', 0)
             if remaining > 0:
                 self.rfile.read(remaining)
-        
+
         if "date" not in hkeys:
             self.outheaders.append(("Date", rfc822.formatdate()))
-        
+
         if "server" not in hkeys:
             self.outheaders.append(("Server", self.server.server_name))
-        
+
         buf = [self.server.protocol + SPACE + self.status + CRLF]
         for k, v in self.outheaders:
             buf.append(k + COLON + SPACE + v + CRLF)
         self.bytes_read = 0
         self.bytes_written = 0
         socket._fileobject.__init__(self, *args, **kwargs)
-    
+
     def sendall(self, data):
         """Sendall for non-blocking sockets."""
         while data:
 
 class HTTPConnection(object):
     """An HTTP connection (active socket).
-    
+
     server: the Server object which received this connection.
     socket: the raw socket object (usually TCP) for this connection.
     makefile: a fileobject class for reading from the socket.
     """
-    
+
     remote_addr = None
     remote_port = None
     ssl_env = None
     rbufsize = DEFAULT_BUFFER_SIZE
     wbufsize = DEFAULT_BUFFER_SIZE
     RequestHandlerClass = HTTPRequest
-    
+
     def __init__(self, server, sock, makefile=CP_fileobject):
         self.server = server
         self.socket = sock
         self.rfile = makefile(sock, "rb", self.rbufsize)
         self.wfile = makefile(sock, "wb", self.wbufsize)
         self.requests_seen = 0
-    
+
     def communicate(self):
         """Read each request and respond appropriately."""
         request_seen = False
                 # get written to the previous request.
                 req = None
                 req = self.RequestHandlerClass(self.server, self)
-                
+
                 # This order of operations should guarantee correct pipelining.
                 req.parse_request()
                 if self.server.stats['Enabled']:
                     # probably already made a simple_response). Return and
                     # let the conn close.
                     return
-                
+
                 request_seen = True
                 req.respond()
                 if req.close_connection:
                 except FatalSSLAlert:
                     # Close the connection.
                     return
-    
+
     linger = False
-    
+
     def close(self):
         """Close the socket underlying this connection."""
         self.rfile.close()
-        
+
         if not self.linger:
             # Python's socket module does NOT call close on the kernel socket
             # when you call socket.close(). We do so manually here because we
 
 class WorkerThread(threading.Thread):
     """Thread which continuously polls a Queue for Connection objects.
-    
+
     Due to the timing issues of polling a Queue, a WorkerThread does not
     check its own 'ready' flag after it has started. To stop the thread,
     it is necessary to stick a _SHUTDOWNREQUEST object onto the Queue
     (one for each running WorkerThread).
     """
-    
+
     conn = None
     """The current connection pulled off the Queue, or None."""
-    
+
     server = None
     """The HTTP Server which spawned this thread, and which owns the
     Queue and is placing active connections into it."""
-    
+
     ready = False
     """A simple flag for the calling server to know when this thread
     has begun polling the Queue."""
-    
-    
+
+
     def __init__(self, server):
         self.ready = False
         self.server = server
-        
+
         self.requests_seen = 0
         self.bytes_read = 0
         self.bytes_written = 0
             'Write Throughput': lambda s: s['Bytes Written'](s) / (s['Work Time'](s) or 1e-6),
         }
         threading.Thread.__init__(self)
-    
+
     def run(self):
         self.server.stats['Worker Threads'][self.getName()] = self.stats
         try:
                 conn = self.server.requests.get()
                 if conn is _SHUTDOWNREQUEST:
                     return
-                
+
                 self.conn = conn
                 if self.server.stats['Enabled']:
                     self.start_time = time.time()
 
 class ThreadPool(object):
     """A Request Queue for an HTTPServer which pools threads.
-    
+
     ThreadPool objects must provide min, get(), put(obj), start()
     and stop(timeout) attributes.
     """
-    
+
     def __init__(self, server, min=10, max=-1):
         self.server = server
         self.min = min
         self._threads = []
         self._queue = queue.Queue()
         self.get = self._queue.get
-    
+
     def start(self):
         """Start the pool of threads."""
         for i in range(self.min):
         for worker in self._threads:
             while not worker.ready:
                 time.sleep(.1)
-    
+
     def _get_idle(self):
         """Number of worker threads which are idle. Read-only."""
         return len([t for t in self._threads if t.conn is None])
     idle = property(_get_idle, doc=_get_idle.__doc__)
-    
+
     def put(self, obj):
         self._queue.put(obj)
         if obj is _SHUTDOWNREQUEST:
             return
-    
+
     def grow(self, amount):
         """Spawn new worker threads (not above self.max)."""
         for i in range(amount):
             worker.setName("CP Server " + worker.getName())
             self._threads.append(worker)
             worker.start()
-    
+
     def shrink(self, amount):
         """Kill off worker threads (not below self.min)."""
         # Grow/shrink the pool if necessary.
             if not t.isAlive():
                 self._threads.remove(t)
                 amount -= 1
-        
+
         if amount > 0:
             for i in range(min(amount, len(self._threads) - self.min)):
                 # Put a number of shutdown requests on the queue equal
                 # that worker will terminate and be culled from our list
                 # in self.put.
                 self._queue.put(_SHUTDOWNREQUEST)
-    
+
     def stop(self, timeout=5):
         # Must shut down threads here so the code that calls
         # this method can know when all threads are stopped.
         for worker in self._threads:
             self._queue.put(_SHUTDOWNREQUEST)
-        
+
         # Don't join currentThread (when stop is called inside a request).
         current = threading.currentThread()
         if timeout and timeout >= 0:
                         # See http://www.cherrypy.org/ticket/691.
                         KeyboardInterrupt):
                     pass
-    
+
     def _get_qsize(self):
         return self._queue.qsize()
     qsize = property(_get_qsize)
 
 class SSLAdapter(object):
     """Base class for SSL driver library adapters.
-    
+
     Required methods:
-    
+
         * ``wrap(sock) -> (wrapped socket, ssl environ dict)``
         * ``makefile(sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE) -> socket file object``
     """
-    
+
     def __init__(self, certificate, private_key, certificate_chain=None):
         self.certificate = certificate
         self.private_key = private_key
         self.certificate_chain = certificate_chain
-    
+
     def wrap(self, sock):
         raise NotImplemented
-    
+
     def makefile(self, sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE):
         raise NotImplemented
 
 
 class HTTPServer(object):
     """An HTTP server."""
-    
+
     _bind_addr = "127.0.0.1"
     _interrupt = None
-    
+
     gateway = None
     """A Gateway instance."""
-    
+
     minthreads = None
     """The minimum number of worker threads to create (default 10)."""
-    
+
     maxthreads = None
     """The maximum number of worker threads to create (default -1 = no limit)."""
-    
+
     server_name = None
     """The name of the server; defaults to socket.gethostname()."""
-    
+
     protocol = "HTTP/1.1"
     """The version string to write in the Status-Line of all HTTP responses.
-    
+
     For example, "HTTP/1.1" is the default. This also limits the supported
     features used in the response."""
-    
+
     request_queue_size = 5
     """The 'backlog' arg to socket.listen(); max queued connections (default 5)."""
-    
+
     shutdown_timeout = 5
     """The total time, in seconds, to wait for worker threads to cleanly exit."""
-    
+
     timeout = 10
     """The timeout in seconds for accepted connections (default 10)."""
-    
+
     version = "CherryPy/3.2.2"
     """A version string for the HTTPServer."""
-    
+
     software = None
     """The value to set for the SERVER_SOFTWARE entry in the WSGI environ.
-    
+
     If None, this defaults to ``'%s Server' % self.version``."""
-    
+
     ready = False
     """An internal flag which marks whether the socket is accepting connections."""
-    
+
     max_request_header_size = 0
     """The maximum size, in bytes, for request headers, or 0 for no limit."""
-    
+
     max_request_body_size = 0
     """The maximum size, in bytes, for request bodies, or 0 for no limit."""
-    
+
     nodelay = True
     """If True (the default since 3.1), sets the TCP_NODELAY socket option."""
-    
+
     ConnectionClass = HTTPConnection
     """The class to use for handling HTTP connections."""
-    
+
     ssl_adapter = None
     """An instance of SSLAdapter (or a subclass).
-    
+
     You must have the corresponding SSL driver library installed."""
-    
+
     def __init__(self, bind_addr, gateway, minthreads=10, maxthreads=-1,
                  server_name=None):
         self.bind_addr = bind_addr
         self.gateway = gateway
-        
+
         self.requests = ThreadPool(self, min=minthreads or 1, max=maxthreads)
-        
+
         if not server_name:
             server_name = socket.gethostname()
         self.server_name = server_name
         self.clear_stats()
-    
+
     def clear_stats(self):
         self._start_time = None
         self._run_time = 0
             'Worker Threads': {},
             }
         logging.statistics["CherryPy HTTPServer %d" % id(self)] = self.stats
-    
+
     def runtime(self):
         if self._start_time is None:
             return self._run_time
         else:
             return self._run_time + (time.time() - self._start_time)
-    
+
     def __str__(self):
         return "%s.%s(%r)" % (self.__module__, self.__class__.__name__,
                               self.bind_addr)
-    
+
     def _get_bind_addr(self):
         return self._bind_addr
     def _set_bind_addr(self, value):
         self._bind_addr = value
     bind_addr = property(_get_bind_addr, _set_bind_addr,
         doc="""The interface on which to listen for connections.
-        
+
         For TCP sockets, a (host, port) tuple. Host values may be any IPv4
         or IPv6 address, or any valid hostname. The string 'localhost' is a
         synonym for '127.0.0.1' (or '::1', if your hosts file prefers IPv6).
         The string '0.0.0.0' is a special IPv4 entry meaning "any active
         interface" (INADDR_ANY), and '::' is the similar IN6ADDR_ANY for
         IPv6. The empty string or None are not allowed.
-        
+
         For UNIX sockets, supply the filename as a string.""")
-    
+
     def start(self):
         """Run the server forever."""
         # We don't have to trap KeyboardInterrupt or SystemExit here,
         # If you're using this server with another framework, you should
         # trap those exceptions in whatever code block calls start().
         self._interrupt = None
-        
+
         if self.software is None:
             self.software = "%s Server" % self.version
-        
+
         # SSL backward compatibility
         if (self.ssl_adapter is None and
             getattr(self, 'ssl_certificate', None) and
                 self.ssl_adapter = pyOpenSSLAdapter(
                     self.ssl_certificate, self.ssl_private_key,
                     getattr(self, 'ssl_certificate_chain', None))
-        
+
         # Select the appropriate socket
         if isinstance(self.bind_addr, basestring):
             # AF_UNIX socket
-            
+
             # So we can reuse the socket...
             try: os.unlink(self.bind_addr)
             except: pass
-            
+
             # So everyone can access the socket...
             try: os.chmod(self.bind_addr, 511) # 0777
             except: pass
-            
+
             info = [(socket.AF_UNIX, socket.SOCK_STREAM, 0, "", self.bind_addr)]
         else:
             # AF_INET or AF_INET6 socket
                 else:
                     info = [(socket.AF_INET, socket.SOCK_STREAM,
                              0, "", self.bind_addr)]
-        
+
         self.socket = None
         msg = "No socket could be created"
         for res in info:
             break
         if not self.socket:
             raise socket.error(msg)
-        
+
         # Timeout so KeyboardInterrupt can be caught on Win32
         self.socket.settimeout(1)
         self.socket.listen(self.request_queue_size)
-        
+
         # Create worker threads
         self.requests.start()
-        
+
         self.ready = True
         self._start_time = time.time()
         while self.ready:
             except:
                 self.error_log("Error in HTTPServer.tick", level=logging.ERROR,
                                traceback=True)
-            
+
             if self.interrupt:
                 while self.interrupt is True:
                     # Wait for self.stop() to complete. See _set_interrupt.
         self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         if self.nodelay and not isinstance(self.bind_addr, str):
             self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
-        
+
         if self.ssl_adapter is not None:
             self.socket = self.ssl_adapter.bind(self.socket)
-        
+
         # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
         # activate dual-stack. See http://www.cherrypy.org/ticket/871.
         if (hasattr(socket, 'AF_INET6') and family == socket.AF_INET6
                 # Apparently, the socket option is not available in
                 # this machine's TCP stack
                 pass
-        
+
         self.socket.bind(self.bind_addr)
-    
+
     def tick(self):
         """Accept a new connection and put it on the Queue."""
         try:
                 self.stats['Accepts'] += 1
             if not self.ready:
                 return
-            
+
             prevent_socket_inheritance(s)
             if hasattr(s, 'settimeout'):
                 s.settimeout(self.timeout)
-            
+
             makefile = CP_fileobject
             ssl_env = {}
             # if ssl cert and key are set, we try to be a secure HTTP server
                            "Content-Length: %s\r\n" % len(msg),
                            "Content-Type: text/plain\r\n\r\n",
                            msg]
-                    
+
                     wfile = makefile(s, "wb", DEFAULT_BUFFER_SIZE)
                     try:
                         wfile.sendall("".join(buf))
                 # Re-apply our timeout since we may have a new socket object
                 if hasattr(s, 'settimeout'):
                     s.settimeout(self.timeout)
-            
+
             conn = self.ConnectionClass(self, s, makefile)
-            
+
             if not isinstance(self.bind_addr, basestring):
                 # optional values
                 # Until we do DNS lookups, omit REMOTE_HOST
                         addr = ('::', 0)
                 conn.remote_addr = addr[0]
                 conn.remote_port = addr[1]
-            
+
             conn.ssl_env = ssl_env
-            
+
             self.requests.put(conn)
         except socket.timeout:
             # The only reason for the timeout in start() is so we can
                 # See http://www.cherrypy.org/ticket/686.
                 return
             raise
-    
+
     def _get_interrupt(self):
         return self._interrupt
     def _set_interrupt(self, interrupt):
     interrupt = property(_get_interrupt, _set_interrupt,
                          doc="Set this to an Exception instance to "
                              "interrupt the server.")
-    
+
     def stop(self):
         """Gracefully shutdown a server that is serving forever."""
         self.ready = False
         if self._start_time is not None:
             self._run_time += (time.time() - self._start_time)
         self._start_time = None
-        
+
         sock = getattr(self, "socket", None)
         if sock:
             if not isinstance(self.bind_addr, basestring):
             if hasattr(sock, "close"):
                 sock.close()
             self.socket = None
-        
+
         self.requests.stop(self.shutdown_timeout)
 
 
 class Gateway(object):
     """A base class to interface HTTPServer with other systems, such as WSGI."""
-    
+
     def __init__(self, req):
         self.req = req
-    
+
     def respond(self):
         """Process the current request. Must be overridden in a subclass."""
         raise NotImplemented
         last_dot = adapter.rfind(".")
         attr_name = adapter[last_dot + 1:]
         mod_path = adapter[:last_dot]
-        
+
         try:
             mod = sys.modules[mod_path]
             if mod is None:
         except KeyError:
             # The last [''] is important.
             mod = __import__(mod_path, globals(), locals(), [''])
-        
+
         # Let an AttributeError propagate outward.
         try:
             adapter = getattr(mod, attr_name)
         except AttributeError:
             raise AttributeError("'%s' object has no attribute '%s'"
                                  % (mod_path, attr_name))
-    
+
     return adapter
 
 # -------------------------------- WSGI Stuff -------------------------------- #
 
 class CherryPyWSGIServer(HTTPServer):
     """A subclass of HTTPServer which calls a WSGI application."""
-    
+
     wsgi_version = (1, 0)
     """The version of WSGI to produce."""
-    
+
     def __init__(self, bind_addr, wsgi_app, numthreads=10, server_name=None,
                  max=-1, request_queue_size=5, timeout=10, shutdown_timeout=5):
         self.requests = ThreadPool(self, min=numthreads or 1, max=max)
         self.wsgi_app = wsgi_app
         self.gateway = wsgi_gateways[self.wsgi_version]
-        
+
         self.bind_addr = bind_addr
         if not server_name:
             server_name = socket.gethostname()
         self.server_name = server_name
         self.request_queue_size = request_queue_size
-        
+
         self.timeout = timeout
         self.shutdown_timeout = shutdown_timeout
         self.clear_stats()
-    
+
     def _get_numthreads(self):
         return self.requests.min
     def _set_numthreads(self, value):
 
 class WSGIGateway(Gateway):
     """A base class to interface HTTPServer with WSGI."""
-    
+
     def __init__(self, req):
         self.req = req
         self.started_response = False
         self.env = self.get_environ()
         self.remaining_bytes_out = None
-    
+
     def get_environ(self):
         """Return a new environ dict targeting the given wsgi.version"""
         raise NotImplemented
-    
+
     def respond(self):
         """Process the current request."""
         response = self.req.server.wsgi_app(self.env, self.start_response)
         finally:
             if hasattr(response, "close"):
                 response.close()
-    
+
     def start_response(self, status, headers, exc_info = None):
         """WSGI callable to begin the HTTP response."""
         # "The application may call start_response more than once,
             raise AssertionError("WSGI start_response called a second "
                                  "time with no exc_info.")
         self.started_response = True
-        
+
         # "if exc_info is provided, and the HTTP headers have already been
         # sent, start_response must raise an error, and should raise the
         # exc_info tuple."
                 raise exc_info[0], exc_info[1], exc_info[2]
             finally:
                 exc_info = None
-        
+
         self.req.status = status
         for k, v in headers:
             if not isinstance(k, str):
             if k.lower() == 'content-length':
                 self.remaining_bytes_out = int(v)
         self.req.outheaders.extend(headers)
-        
+
         return self.write
-    
+
     def write(self, chunk):
         """WSGI callable to write unbuffered data to the client.
-        
+
         This method is also used internally by start_response (to write
         data from the iterable returned by the WSGI application).
         """
         if not self.started_response:
             raise AssertionError("WSGI write called before start_response.")
-        
+
         chunklen = len(chunk)
         rbo = self.remaining_bytes_out
         if rbo is not None and chunklen > rbo:
                 # Dang. We have probably already sent data. Truncate the chunk
                 # to fit (so the client doesn't hang) and raise an error later.
                 chunk = chunk[:rbo]
-        
+
         if not self.req.sent_headers:
             self.req.sent_headers = True
             self.req.send_headers()
-        
+
         self.req.write(chunk)
-        
+
         if rbo is not None:
             rbo -= chunklen
             if rbo < 0:
 
 class WSGIGateway_10(WSGIGateway):
     """A Gateway class to interface HTTPServer with WSGI 1.0.x."""
-    
+
     def get_environ(self):
         """Return a new environ dict targeting the given wsgi.version"""
         req = self.req
             'wsgi.url_scheme': req.scheme,
             'wsgi.version': (1, 0),
             }
-        
+
         if isinstance(req.server.bind_addr, basestring):
             # AF_UNIX. This isn't really allowed by WSGI, which doesn't
             # address unix domain sockets. But it's better than nothing.
             env["SERVER_PORT"] = ""
         else:
             env["SERVER_PORT"] = str(req.server.bind_addr[1])
-        
+
         # Request headers
         for k, v in req.inheaders.iteritems():
             env["HTTP_" + k.upper().replace("-", "_")] = v
-        
+
         # CONTENT_TYPE/CONTENT_LENGTH
         ct = env.pop("HTTP_CONTENT_TYPE", None)
         if ct is not None:
         cl = env.pop("HTTP_CONTENT_LENGTH", None)
         if cl is not None:
             env["CONTENT_LENGTH"] = cl
-        
+
         if req.conn.ssl_env:
             env.update(req.conn.ssl_env)
-        
+
         return env
 
 
 class WSGIGateway_u0(WSGIGateway_10):
     """A Gateway class to interface HTTPServer with WSGI u.0.
-    
+
     WSGI u.0 is an experimental protocol, which uses unicode for keys and values
     in both Python 2 and Python 3.
     """
-    
+
     def get_environ(self):
         """Return a new environ dict targeting the given wsgi.version"""
         req = self.req
         env_10 = WSGIGateway_10.get_environ(self)
         env = dict([(k.decode('ISO-8859-1'), v) for k, v in env_10.iteritems()])
         env[u'wsgi.version'] = ('u', 0)
-        
+
         # Request-URI
         env.setdefault(u'wsgi.url_encoding', u'utf-8')
         try:
             env[u'wsgi.url_encoding'] = u'ISO-8859-1'
             for key in [u"PATH_INFO", u"SCRIPT_NAME", u"QUERY_STRING"]:
                 env[key] = env_10[str(key)].decode(env[u'wsgi.url_encoding'])
-        
+
         for k, v in sorted(env.items()):
             if isinstance(v, str) and k not in ('REQUEST_URI', 'wsgi.input'):
                 env[k] = v.decode('ISO-8859-1')
-        
+
         return env
 
 wsgi_gateways = {
 
 class WSGIPathInfoDispatcher(object):
     """A WSGI dispatcher for dispatch based on the PATH_INFO.
-    
+
     apps: a dict or list of (path_prefix, app) pairs.
     """
-    
+
     def __init__(self, apps):
         try:
             apps = list(apps.items())
         except AttributeError:
             pass
-        
+
         # Sort the apps by len(path), descending
         apps.sort(cmp=lambda x,y: cmp(len(x[0]), len(y[0])))
         apps.reverse()
-        
+
         # The path_prefix strings must start, but not end, with a slash.
         # Use "" instead of "/".
         self.apps = [(p.rstrip("/"), a) for p, a in apps]
-    
+
     def __call__(self, environ, start_response):
         path = environ["PATH_INFO"] or "/"
         for p, app in self.apps:
                 environ["SCRIPT_NAME"] = environ["SCRIPT_NAME"] + p
                 environ["PATH_INFO"] = path[len(p):]
                 return app(environ, start_response)
-        
+
         start_response('404 Not Found', [('Content-Type', 'text/plain'),
                                          ('Content-Length', '0')])
         return ['']

cherrypy/wsgiserver/wsgiserver3.py

 (without using CherryPy's application machinery)::
 
     from cherrypy import wsgiserver
-    
+
     def my_crazy_app(environ, start_response):
         status = '200 OK'
         response_headers = [('Content-type','text/plain')]
         start_response(status, response_headers)
         return ['Hello world!']
-    
+
     server = wsgiserver.CherryPyWSGIServer(
                 ('0.0.0.0', 8070), my_crazy_app,
                 server_name='www.cherrypy.example')
     server.start()
-    
-The CherryPy WSGI server can serve as many WSGI applications 
+
+The CherryPy WSGI server can serve as many WSGI applications
 as you want in one instance by using a WSGIPathInfoDispatcher::
-    
+
     d = WSGIPathInfoDispatcher({'/': my_crazy_app, '/blog': my_blog_app})
     server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 80), d)
-    
+
 Want SSL support? Just set server.ssl_adapter to an SSLAdapter instance.
 
 This won't call the CherryPy engine (application side) at all, only the
 
 def plat_specific_errors(*errnames):
     """Return error numbers for all errors in errnames on this platform.
-    
+
     The 'errno' module contains different global constants depending on
     the specific platform (OS). This function will return the list of
     numeric values for a given list of potential names.
 
 def read_headers(rfile, hdict=None):
     """Read headers from the given stream into the given header dict.
-    
+
     If hdict is None, a new header dict is created. Returns the populated
     header dict.
-    
+
     Headers which are repeated are folded together using a comma if their
     specification so dictates.
-    
+
     This function raises ValueError when the read bytes violate the HTTP spec.
     You should probably return "400 Bad Request" if this happens.
     """
     if hdict is None:
         hdict = {}
-    
+
     while True:
         line = rfile.readline()
         if not line:
             # No more data--illegal end of headers
             raise ValueError("Illegal end of headers.")
-        
+
         if line == CRLF:
             # Normal end of headers
             break
         if not line.endswith(CRLF):
             raise ValueError("HTTP requires CRLF terminators")
-        
+
         if line[0] in (SPACE, TAB):
             # It's a continuation line.
             v = line.strip()
             k = k.strip().title()
             v = v.strip()
             hname = k
-        
+
         if k in comma_separated_headers:
             existing = hdict.get(hname)
             if existing:
                 v = b", ".join((existing, v))
         hdict[hname] = v
-    
+
     return hdict
 
 
 
 class SizeCheckWrapper(object):
     """Wraps a file-like object, raising MaxSizeExceeded if too large."""
-    
+
     def __init__(self, rfile, maxlen):
         self.rfile = rfile
         self.maxlen = maxlen
         self.bytes_read = 0
-    
+
     def _check_length(self):
         if self.maxlen and self.bytes_read > self.maxlen:
             raise MaxSizeExceeded()
-    
+
     def read(self, size=None):
         data = self.rfile.read(size)
         self.bytes_read += len(data)
         self._check_length()
         return data
-    
+
     def readline(self, size=None):
         if size is not None:
             data = self.rfile.readline(size)
             self.bytes_read += len(data)
             self._check_length()
             return data
-        
+
         # User didn't specify a size ...
         # We read the line in chunks to make sure it's not a 100MB line !
         res = []
             # See http://www.cherrypy.org/ticket/421
             if len(data) < 256 or data[-1:] == "\n":
                 return EMPTY.join(res)
-    
+
     def readlines(self, sizehint=0):
         # Shamelessly stolen from StringIO
         total = 0
                 break
             line = self.readline()
         return lines
-    
+
     def close(self):
         self.rfile.close()
-    
+
     def __iter__(self):
         return self
-    
+
     def __next__(self):
         data = next(self.rfile)
         self.bytes_read += len(data)
         self._check_length()
         return data
-    
+
     def next(self):
         data = self.rfile.next()
         self.bytes_read += len(data)
 
 class KnownLengthRFile(object):
     """Wraps a file-like object, returning an empty string when exhausted."""
-    
+
     def __init__(self, rfile, content_length):
         self.rfile = rfile
         self.remaining = content_length
-    
+
     def read(self, size=None):
         if self.remaining == 0:
             return b''
             size = self.remaining
         else:
             size = min(size, self.remaining)
-        
+
         data = self.rfile.read(size)
         self.remaining -= len(data)
         return data
-    
+
     def readline(self, size=None):
         if self.remaining == 0:
             return b''
             size = self.remaining
         else:
             size = min(size, self.remaining)
-        
+
         data = self.rfile.readline(size)
         self.remaining -= len(data)
         return data
-    
+
     def readlines(self, sizehint=0):
         # Shamelessly stolen from StringIO
         total = 0
                 break
             line = self.readline(sizehint)
         return lines
-    
+
     def close(self):
         self.rfile.close()
-    
+
     def __iter__(self):
         return self
-    
+
     def __next__(self):
         data = next(self.rfile)
         self.remaining -= len(data)
 
 class ChunkedRFile(object):
     """Wraps a file-like object, returning an empty string when exhausted.
-    
+
     This class is intended to provide a conforming wsgi.input value for
     request entities that have been encoded with the 'chunked' transfer
     encoding.
     """
-    
+
     def __init__(self, rfile, maxlen, bufsize=8192):
         self.rfile = rfile
         self.maxlen = maxlen
         self.buffer = EMPTY
         self.bufsize = bufsize
         self.closed = False
-    
+
     def _fetch(self):
         if self.closed:
             return
-        
+
         line = self.rfile.readline()
         self.bytes_read += len(line)
-        
+
         if self.maxlen and self.bytes_read > self.maxlen:
             raise MaxSizeExceeded("Request Entity Too Large", self.maxlen)
-        
+
         line = line.strip().split(SEMICOLON, 1)
-        
+
         try:
             chunk_size = line.pop(0)
             chunk_size = int(chunk_size, 16)
         except ValueError:
             raise ValueError("Bad chunked transfer size: " + repr(chunk_size))
-        
+
         if chunk_size <= 0:
             self.closed = True
             return
-        
+
 ##            if line: chunk_extension = line[0]
-        
+
         if self.maxlen and self.bytes_read + chunk_size > self.maxlen:
             raise IOError("Request Entity Too Large")
-        
+
         chunk = self.rfile.read(chunk_size)
         self.bytes_read += len(chunk)
         self.buffer += chunk
-        
+
         crlf = self.rfile.read(2)
         if crlf != CRLF:
             raise ValueError(
                  "Bad chunked transfer coding (expected '\\r\\n', "
                  "got " + repr(crlf) + ")")
-    
+
     def read(self, size=None):
         data = EMPTY
         while True:
             if size and len(data) >= size:
                 return data
-            
+
             if not self.buffer:
                 self._fetch()
                 if not self.buffer:
                     # EOF
                     return data
-            
+
             if size:
                 remaining = size - len(data)
                 data += self.buffer[:remaining]
                 self.buffer = self.buffer[remaining:]
             else:
                 data += self.buffer
-    
+
     def readline(self, size=None):
         data = EMPTY
         while True:
             if size and len(data) >= size:
                 return data
-            
+
             if not self.buffer:
                 self._fetch()
                 if not self.buffer:
                     # EOF
                     return data
-            
+
             newline_pos = self.buffer.find(LF)
             if size:
                 if newline_pos == -1:
                 else:
                     data += self.buffer[:newline_pos]
                     self.buffer = self.buffer[newline_pos:]
-    
+
     def readlines(self, sizehint=0):
         # Shamelessly stolen from StringIO
         total = 0
                 break
             line = self.readline(sizehint)
         return lines
-    
+
     def read_trailer_lines(self):
         if not self.closed:
             raise ValueError(
                 "Cannot read trailers until the request body has been read.")
-        
+
         while True:
             line = self.rfile.readline()
             if not line:
                 # No more data--illegal end of headers
                 raise ValueError("Illegal end of headers.")
-            
+
             self.bytes_read += len(line)
             if self.maxlen and self.bytes_read > self.maxlen:
                 raise IOError("Request Entity Too Large")
-            
+
             if line == CRLF:
                 # Normal end of headers
                 break
             if not line.endswith(CRLF):
                 raise ValueError("HTTP requires CRLF terminators")
-            
+
             yield line
-    
+
     def close(self):
         self.rfile.close()
-    
+
     def __iter__(self):
         # Shamelessly stolen from StringIO
         total = 0
 
 class HTTPRequest(object):
     """An HTTP Request (and response).
-    
+
     A single HTTP connection may consist of multiple request/response pairs.
     """
-    
+
     server = None
     """The HTTPServer object which is receiving this request."""
-    
+
     conn = None
     """The HTTPConnection object on which this request connected."""
-    
+
     inheaders = {}
     """A dict of request headers."""
-    
+
     outheaders = []
     """A list of header tuples to write in the response."""
-    
+
     ready = False
     """When True, the request has been parsed and is ready to begin generating
     the response. When False, signals the calling Connection that the response
     should not be generated and the connection should close."""
-    
+
     close_connection = False
     """Signals the calling Connection that the request should close. This does
     not imply an error! The client and/or server may each request that the
     connection be closed."""
-    
+
     chunked_write = False
     """If True, output will be encoded with the "chunked" transfer-coding.
-    
+
     This value is set automatically inside send_headers."""
-    
+
     def __init__(self, server, conn):
         self.server= server
         self.conn = conn
-        
+
         self.ready = False
         self.started_request = False
         self.scheme = ntob("http")
         # Use the lowest-common protocol in case read_request_line errors.
         self.response_protocol = 'HTTP/1.0'
         self.inheaders = {}
-        
+
         self.status = ""
         self.outheaders = []
         self.sent_headers = False
         self.close_connection = self.__class__.close_connection
         self.chunked_read = False
         self.chunked_write = self.__class__.chunked_write
-    
+
     def parse_request(self):
         """Parse the next HTTP request start-line and message-headers."""
         self.rfile = SizeCheckWrapper(self.conn.rfile,
         else:
             if not success:
                 return
-        
+
         try:
             success = self.read_request_headers()
         except MaxSizeExceeded:
         else:
             if not success:
                 return
-        
+
         self.ready = True
-    
+
     def read_request_line(self):
         # HTTP/1.1 connections are persistent by default. If a client
         # requests a page, then idles (leaves the connection open),
         # (although your TCP stack might suffer for it: cf Apache's history
         # with FIN_WAIT_2).
         request_line = self.rfile.readline()
-        
+
         # Set started_request to True so communicate() knows to send 408
         # from here on out.
         self.started_request = True
         if not request_line:
             return False
-        
+
         if request_line == CRLF:
             # RFC 2616 sec 4.1: "...if the server is reading the protocol
             # stream at the beginning of a message and receives a CRLF
             request_line = self.rfile.readline()
             if not request_line:
                 return False
-        
+
         if not request_line.endswith(CRLF):
             self.simple_response("400 Bad Request", "HTTP requires CRLF terminators")
             return False
-        
+
         try:
             method, uri, req_protocol = request_line.strip().split(SPACE, 2)
             # The [x:y] slicing is necessary for byte strings to avoid getting ord's
         except ValueError:
             self.simple_response("400 Bad Request", "Malformed Request-Line")
             return False
-        
+
         self.uri = uri
         self.method = method
-        
+
         # uri may be an abs_path (including "http://host.domain.tld");
         scheme, authority, path = self.parse_request_uri(uri)
         if NUMBER_SIGN in path:
             self.simple_response("400 Bad Request",
                                  "Illegal #fragment in Request-URI.")
             return False