Source

CherryPy / cherrypy / _cptree.py

Diff from to

cherrypy/_cptree.py

 """CherryPy Application and Tree objects."""
 
 import os
-import sys
 import cherrypy
-from cherrypy import _cpconfig, _cplogging, tools
-from cherrypy._cperror import format_exc, bare_error
-from cherrypy.lib import http
+from cherrypy import _cpconfig, _cplogging, _cpwsgi, tools
 
 
 class Application(object):
         self.log = _cplogging.LogManager(id(self))
         self.root = root
         self.script_name = script_name
+        self.wsgiapp = _cpwsgi.CPWSGIApp(self)
         self.namespaces = {"log": lambda k, v: setattr(self.log, k, v),
+                           "wsgi": self.wsgiapp.namespace_handler,
                            }
         self.config = {}
     
         # Handle namespaces specified in config.
         _cpconfig._call_namespaces(self.config.get("/", {}), self.namespaces)
     
-    def wsgiapp(self, environ, start_response):
-        # This is here instead of __call__ because it's really hard
-        # to overwrite special methods like __call__ per instance.
-        return wsgi_handler(environ, start_response, app=self)
-    
     def __call__(self, environ, start_response):
         return self.wsgiapp(environ, start_response)
 
 
-headerNames = {'HTTP_CGI_AUTHORIZATION': 'Authorization',
-               'CONTENT_LENGTH': 'Content-Length',
-               'CONTENT_TYPE': 'Content-Type',
-               'REMOTE_HOST': 'Remote-Host',
-               'REMOTE_ADDR': 'Remote-Addr',
-               }
-
-def translate_headers(environ):
-    """Translate CGI-environ header names to HTTP header names."""
-    for cgiName in environ:
-        # We assume all incoming header keys are uppercase already.
-        if cgiName in headerNames:
-            yield headerNames[cgiName], environ[cgiName]
-        elif cgiName[:5] == "HTTP_":
-            # Hackish attempt at recovering original header names.
-            translatedHeader = cgiName[5:].replace("_", "-")
-            yield translatedHeader, environ[cgiName]
-
-
-def wsgi_handler(environ, start_response, app):
-    request = None
-    try:
-        env = environ.get
-        local = http.Host('', int(env('SERVER_PORT', 80)),
-                          env('SERVER_NAME', ''))
-        remote = http.Host(env('REMOTE_ADDR', ''),
-                           int(env('REMOTE_PORT', -1)),
-                           env('REMOTE_HOST', ''))
-        request = cherrypy.engine.request(local, remote,
-                                          env('wsgi.url_scheme'),
-                                          env('ACTUAL_SERVER_PROTOCOL', "HTTP/1.1"))
-        
-        # LOGON_USER is served by IIS, and is the name of the
-        # user after having been mapped to a local account.
-        # Both IIS and Apache set REMOTE_USER, when possible.
-        request.login = env('LOGON_USER') or env('REMOTE_USER') or None
-        
-        request.multithread = environ['wsgi.multithread']
-        request.multiprocess = environ['wsgi.multiprocess']
-        request.wsgi_environ = environ
-        
-        request.app = app
-        
-        path = env('SCRIPT_NAME', '') + env('PATH_INFO', '')
-        response = request.run(environ['REQUEST_METHOD'], path,
-                               env('QUERY_STRING', ''),
-                               env('SERVER_PROTOCOL'),
-                               translate_headers(environ),
-                               environ['wsgi.input'])
-        s, h, b = response.status, response.header_list, response.body
-        exc = None
-    except (KeyboardInterrupt, SystemExit), ex:
-        try:
-            if request:
-                request.close()
-        except:
-            cherrypy.log(traceback=True)
-        request = None
-        raise ex
-    except:
-        if request and request.throw_errors:
-            raise
-        tb = format_exc()
-        cherrypy.log(tb)
-        if request and not request.show_tracebacks:
-            tb = ""
-        s, h, b = bare_error(tb)
-        exc = sys.exc_info()
-    
-    try:
-        start_response(s, h, exc)
-        for chunk in b:
-            # WSGI requires all data to be of type "str". This coercion should
-            # not take any time at all if chunk is already of type "str".
-            # If it's unicode, it could be a big performance hit (x ~500).
-            if not isinstance(chunk, str):
-                chunk = chunk.encode("ISO-8859-1")
-            yield chunk
-        if request:
-            request.close()
-        request = None
-    except (KeyboardInterrupt, SystemExit), ex:
-        try:
-            if request:
-                request.close()
-        except:
-            cherrypy.log(traceback=True)
-        request = None
-        raise ex
-    except:
-        cherrypy.log(traceback=True)
-        try:
-            if request:
-                request.close()
-        except:
-            cherrypy.log(traceback=True)
-        request = None
-        s, h, b = bare_error()
-        # CherryPy test suite expects bare_error body to be output,
-        # so don't call start_response (which, according to PEP 333,
-        # may raise its own error at that point).
-        for chunk in b:
-            if not isinstance(chunk, str):
-                chunk = chunk.encode("ISO-8859-1")
-            yield chunk
-
-
 class Tree(object):
     """A registry of CherryPy applications, mounted at diverse points.