def handler(self, environ, start_response):
        """Proxy for requests to the actual http server"""
        logger = logging.getLogger(__name__ + '.WSGIProxyApplication.handler')
        url = urlparse(reconstruct_url(environ, self.port))

        # Create connection object
        try:
            connection = self.connection_class(url.netloc)
            # Build path
            path = url.geturl().replace('%s://%s' % (url.scheme, url.netloc),
                                        '')
        except Exception:
            start_response('501 Gateway Error', [('Content-Type', 'text/html')])
            logger.exception('Could not Connect')
            yield '<H1>Could not connect</H1>'
            return

        # Read in request body if it exists
        body = length = None
        try:
            length = int(environ['CONTENT_LENGTH'])
        except (KeyError, ValueError):

            # This is a situation where client HTTP POST is missing content-length.
            # This is also situation where (WebOb?) may screw up encoding and isert extranous = in the body.
            # https://github.com/ipython/ipython/issues/8416
            if environ["REQUEST_METHOD"] == "POST":
                if environ.get("CONTENT_TYPE") == 'application/x-www-form-urlencoded; charset=UTF-8':
                    body = environ['wsgi.input'].read()
                    try:
                        body = unquote_plus(body.decode("utf-8"))

                        # Fix extra = at end of JSON payload
                        if body.startswith("{") and body.endswith("}="):
                            body = body[0:len(body) - 1]

                    except Exception as e:
                        logger.exception(e)
                        logger.error("Could not decode body: %s", body)

                    length = len(body)
        else:
            body = environ['wsgi.input'].read(length)

        # Build headers
        logger.debug('environ = %r', environ)
        headers = dict(
            (key, value)
            for key, value in (
                # This is a hacky way of getting the header names right
                (key[5:].lower().replace('_', '-'), value)
                for key, value in environ.items()
                # Keys that start with HTTP_ are all headers
                if key.startswith('HTTP_')
            )
            if not is_hop_by_hop(key)
        )

        # Handler headers that aren't HTTP_ in environ
        try:
            headers['content-type'] = environ['CONTENT_TYPE']
        except KeyError:
            pass

        # Add our host if one isn't defined
        if 'host' not in headers:
            headers['host'] = environ['SERVER_NAME']

        # Make the remote request
        try:

            logger.debug('%s %s %r',
                         environ['REQUEST_METHOD'], path, headers)
            connection.request(environ['REQUEST_METHOD'], path,
                               body=body, headers=headers)
        except Exception as e:
            # We need extra exception handling in the case the server fails
            # in mid connection, it's an edge case but I've seen it
            if isinstance(e, ConnectionRefusedError):
                # The notebook was shutdown by the user
                pass
            else:
                # This might be a genuine error
                logger.exception(e)

            start_response('501 Gateway Error', [('Content-Type', 'text/html')])
            yield '<H1>Could not proxy IPython Notebook running localhost:{}</H1>'.format(self.port).encode("utf-8")
            return

        try:
            response = connection.getresponse()
        except ConnectionResetError:
            # Notebook shutdown
            start_response('501 Gateway Error', [('Content-Type', 'text/html')])
            yield '<H1>Could not proxy IPython Notebook running localhost:{}</H1>'.format(self.port).encode("utf-8")
            return

        hopped_headers = response.getheaders()
        headers = [(key, value)
                   for key, value in hopped_headers
                   if not is_hop_by_hop(key)]

        start_response('{0.status} {0.reason}'.format(response), headers)
        while True:
            chunk = response.read(4096)
            if chunk:
                yield chunk
            else:
                break
def handler ( self , environ , start_response ) : logger = logging . getLogger ( __name__ + '.WSGIProxyApplication.handler' ) url = urlparse ( reconstruct_url ( environ , self . port ) ) try : connection = self . connection_class ( url . netloc ) path = url . geturl ( ) . replace ( '%s://%s' % ( url . scheme , url . netloc ) , '' ) except Exception : start_response ( '501 Gateway Error' , [ ( 'Content-Type' , 'text/html' ) ] ) logger . exception ( 'Could not Connect' ) yield '<H1>Could not connect</H1>' return body = length = None try : length = int ( environ [ 'CONTENT_LENGTH' ] ) except ( KeyError , ValueError ) : if environ [ "REQUEST_METHOD" ] == "POST" : if environ . get ( "CONTENT_TYPE" ) == 'application/x-www-form-urlencoded; charset=UTF-8' : body = environ [ 'wsgi.input' ] . read ( ) try : body = unquote_plus ( body . decode ( "utf-8" ) ) if body . startswith ( "{" ) and body . endswith ( "}=" ) : body = body [ 0 : len ( body ) - 1 ] except Exception as e : logger . exception ( e ) logger . error ( "Could not decode body: %s" , body ) length = len ( body ) else : body = environ [ 'wsgi.input' ] . read ( length ) logger . debug ( 'environ = %r' , environ ) headers = dict ( ( key , value ) for key , value in ( ( key [ 5 : ] . lower ( ) . replace ( '_' , '-' ) , value ) for key , value in environ . items ( ) if key . startswith ( 'HTTP_' ) ) if not is_hop_by_hop ( key ) ) try : headers [ 'content-type' ] = environ [ 'CONTENT_TYPE' ] except KeyError : pass if 'host' not in headers : headers [ 'host' ] = environ [ 'SERVER_NAME' ] try : logger . debug ( '%s %s %r' , environ [ 'REQUEST_METHOD' ] , path , headers ) connection . request ( environ [ 'REQUEST_METHOD' ] , path , body = body , headers = headers ) except Exception as e : if isinstance ( e , ConnectionRefusedError ) : pass else : logger . exception ( e ) start_response ( '501 Gateway Error' , [ ( 'Content-Type' , 'text/html' ) ] ) yield '<H1>Could not proxy IPython Notebook running localhost:{}</H1>' . format ( self . port ) . encode ( "utf-8" ) return try : response = connection . getresponse ( ) except ConnectionResetError : start_response ( '501 Gateway Error' , [ ( 'Content-Type' , 'text/html' ) ] ) yield '<H1>Could not proxy IPython Notebook running localhost:{}</H1>' . format ( self . port ) . encode ( "utf-8" ) return hopped_headers = response . getheaders ( ) headers = [ ( key , value ) for key , value in hopped_headers if not is_hop_by_hop ( key ) ] start_response ( '{0.status} {0.reason}' . format ( response ) , headers ) while True : chunk = response . read ( 4096 ) if chunk : yield chunk else : break
Proxy for requests to the actual http server