Commits

Robert Brewer committed 043f1fd

Fixed xmlrpc import error in py3, and synced with py2

Comments (0)

Files changed (13)

py2/cherrypy/_cpcompat.py

     # Python 2
     def next(i):
         return i.next()
-

py2/cherrypy/_cpdispatch.py

 
 
 def XMLRPCDispatcher(next_dispatcher=Dispatcher()):
-    from cherrypy.lib import xmlrpc
+    from cherrypy.lib import xmlrpcutil
     def xmlrpc_dispatch(path_info):
-        path_info = xmlrpc.patched_path(path_info)
+        path_info = xmlrpcutil.patched_path(path_info)
         return next_dispatcher(path_info)
     return xmlrpc_dispatch
 

py2/cherrypy/_cptools.py

 #                              Builtin tools                              #
 
 from cherrypy.lib import cptools, encoding, auth, static, jsontools
-from cherrypy.lib import sessions as _sessions, xmlrpc as _xmlrpc
+from cherrypy.lib import sessions as _sessions, xmlrpcutil as _xmlrpc
 from cherrypy.lib import caching as _caching
 from cherrypy.lib import auth_basic, auth_digest
 
             # http://www.cherrypy.org/ticket/533
             # if a method is not found, an xmlrpclib.Fault should be returned
             # raising an exception here will do that; see
-            # cherrypy.lib.xmlrpc.on_error
+            # cherrypy.lib.xmlrpcutil.on_error
             raise Exception('method "%s" is not supported' % attr)
         
         conf = cherrypy.serving.request.toolmaps['tools'].get("xmlrpc", {})

py2/cherrypy/lib/xmlrpc.py

-import sys
-
-import cherrypy
-from cherrypy._cpcompat import ntob
-
-def process_body():
-    """Return (params, method) from request body."""
-    try:
-        # Python 3
-        from xmlrpc.client import loads
-    except ImportError:
-        # Python 2
-        from xmlrpclib import loads
-    
-    try:
-        return loads(cherrypy.request.body.read())
-    except Exception:
-        return ('ERROR PARAMS', ), 'ERRORMETHOD'
-
-
-def patched_path(path):
-    """Return 'path', doctored for RPC."""
-    if not path.endswith('/'):
-        path += '/'
-    if path.startswith('/RPC2/'):
-        # strip the first /rpc2
-        path = path[5:]
-    return path
-
-
-def _set_response(body):
-    # The XML-RPC spec (http://www.xmlrpc.com/spec) says:
-    # "Unless there's a lower-level error, always return 200 OK."
-    # Since Python's xmlrpclib interprets a non-200 response
-    # as a "Protocol Error", we'll just return 200 every time.
-    response = cherrypy.response
-    response.status = '200 OK'
-    response.body = ntob(body, 'utf-8')
-    response.headers['Content-Type'] = 'text/xml'
-    response.headers['Content-Length'] = len(body)
-
-
-def respond(body, encoding='utf-8', allow_none=0):
-    try:
-        # Python 2
-        from xmlrpclib import Fault, dumps
-    except ImportError:
-        # Python 3
-        from xmlrpc.client import Fault, dumps
-    if not isinstance(body, Fault):
-        body = (body,)
-    _set_response(dumps(body, methodresponse=1,
-                        encoding=encoding,
-                        allow_none=allow_none))
-
-def on_error(*args, **kwargs):
-    body = str(sys.exc_info()[1])
-    try:
-        # Python 2
-        from xmlrpclib import Fault, dumps
-    except ImportError:
-        # Python 3
-        from xmlrpc.client import Fault, dumps
-    _set_response(dumps(Fault(1, body)))
-

py2/cherrypy/lib/xmlrpcutil.py

+import sys
+
+import cherrypy
+from cherrypy._cpcompat import ntob
+
+def get_xmlrpclib():
+    try:
+        import xmlrpc.client as x
+    except ImportError:
+        import xmlrpclib as x
+    return x
+
+def process_body():
+    """Return (params, method) from request body."""
+    try:
+        return get_xmlrpclib().loads(cherrypy.request.body.read())
+    except Exception:
+        return ('ERROR PARAMS', ), 'ERRORMETHOD'
+
+
+def patched_path(path):
+    """Return 'path', doctored for RPC."""
+    if not path.endswith('/'):
+        path += '/'
+    if path.startswith('/RPC2/'):
+        # strip the first /rpc2
+        path = path[5:]
+    return path
+
+
+def _set_response(body):
+    # The XML-RPC spec (http://www.xmlrpc.com/spec) says:
+    # "Unless there's a lower-level error, always return 200 OK."
+    # Since Python's xmlrpclib interprets a non-200 response
+    # as a "Protocol Error", we'll just return 200 every time.
+    response = cherrypy.response
+    response.status = '200 OK'
+    response.body = ntob(body, 'utf-8')
+    response.headers['Content-Type'] = 'text/xml'
+    response.headers['Content-Length'] = len(body)
+
+
+def respond(body, encoding='utf-8', allow_none=0):
+    xmlrpclib = get_xmlrpclib()
+    if not isinstance(body, xmlrpclib.Fault):
+        body = (body,)
+    _set_response(xmlrpclib.dumps(body, methodresponse=1,
+                                  encoding=encoding,
+                                  allow_none=allow_none))
+
+def on_error(*args, **kwargs):
+    body = str(sys.exc_info()[1])
+    xmlrpclib = get_xmlrpclib()
+    _set_response(xmlrpclib.dumps(xmlrpclib.Fault(1, body)))
+

py2/cherrypy/test/test_http.py

         self.assertStatus(400)
         self.body = response.fp.read(20)
         self.assertBody("Illegal header line.")
+    
+    def test_http_over_https(self):
+        if self.scheme != 'https':
+            return self.skip("skipped (not running HTTPS)... ")
+        
+        # Try connecting without SSL.
+        conn = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
+        conn.putrequest("GET", "/", skip_host=True)
+        conn.putheader("Host", self.HOST)
+        conn.endheaders()
+        response = conn.response_class(conn.sock, method="GET")
+        response.begin()
+        self.assertEqual(response.status, 400)
+        self.body = response.read()
+        self.assertBody("The client sent a plain HTTP request, but this "
+                        "server only speaks HTTPS on this port.")
 

py2/cherrypy/test/test_xmlrpc.py

 import sys
-from xmlrpclib import DateTime, Fault, ServerProxy, SafeTransport
+from cherrypy._cpcompat import py3k
 
-class HTTPSTransport(SafeTransport):
-    """Subclass of SafeTransport to fix sock.recv errors (by using file)."""
-    
-    def request(self, host, handler, request_body, verbose=0):
-        # issue XML-RPC request
-        h = self.make_connection(host)
-        if verbose:
-            h.set_debuglevel(1)
+try:
+    from xmlrpclib import DateTime, Fault, ProtocolError, ServerProxy, SafeTransport
+except ImportError:
+    from xmlrpc.client import DateTime, Fault, ProtocolError, ServerProxy, SafeTransport
+
+if py3k:
+    HTTPSTransport = SafeTransport
+
+    # Python 3.0's SafeTransport still mistakenly checks for socket.ssl
+    import socket
+    if not hasattr(socket, "ssl"):
+        socket.ssl = True
+else:
+    class HTTPSTransport(SafeTransport):
+        """Subclass of SafeTransport to fix sock.recv errors (by using file)."""
         
-        self.send_request(h, handler, request_body)
-        self.send_host(h, host)
-        self.send_user_agent(h)
-        self.send_content(h, request_body)
-        
-        errcode, errmsg, headers = h.getreply()
-        if errcode != 200:
-            raise xmlrpclib.ProtocolError(host + handler, errcode, errmsg,
-                                          headers)
-        
-        self.verbose = verbose
-        
-        # Here's where we differ from the superclass. It says:
-        # try:
-        #     sock = h._conn.sock
-        # except AttributeError:
-        #     sock = None
-        # return self._parse_response(h.getfile(), sock)
-        
-        return self.parse_response(h.getfile())
+        def request(self, host, handler, request_body, verbose=0):
+            # issue XML-RPC request
+            h = self.make_connection(host)
+            if verbose:
+                h.set_debuglevel(1)
+            
+            self.send_request(h, handler, request_body)
+            self.send_host(h, host)
+            self.send_user_agent(h)
+            self.send_content(h, request_body)
+            
+            errcode, errmsg, headers = h.getreply()
+            if errcode != 200:
+                raise ProtocolError(host + handler, errcode, errmsg, headers)
+            
+            self.verbose = verbose
+            
+            # Here's where we differ from the superclass. It says:
+            # try:
+            #     sock = h._conn.sock
+            # except AttributeError:
+            #     sock = None
+            # return self._parse_response(h.getfile(), sock)
+            
+            return self.parse_response(h.getfile())
 
 import cherrypy
 
     setup_server = staticmethod(setup_server)
     def testXmlRpc(self):
         
-        scheme = "http"
-        try:
-            scheme = self.harness.scheme
-        except AttributeError:
-            pass
-        
+        scheme = self.scheme
         if scheme == "https":
             url = 'https://%s:%s/xmlrpc/' % (self.interface(), self.PORT)
             proxy = ServerProxy(url, transport=HTTPSTransport())

py3/cherrypy/_cpcompat.py

     # Python 2
     def next(i):
         return i.next()
-

py3/cherrypy/_cpdispatch.py

 
 
 def XMLRPCDispatcher(next_dispatcher=Dispatcher()):
-    from cherrypy.lib import xmlrpc
+    from cherrypy.lib import xmlrpcutil
     def xmlrpc_dispatch(path_info):
-        path_info = xmlrpc.patched_path(path_info)
+        path_info = xmlrpcutil.patched_path(path_info)
         return next_dispatcher(path_info)
     return xmlrpc_dispatch
 

py3/cherrypy/_cptools.py

 #                              Builtin tools                              #
 
 from cherrypy.lib import cptools, encoding, auth, static, jsontools
-from cherrypy.lib import sessions as _sessions, xmlrpc as _xmlrpc
+from cherrypy.lib import sessions as _sessions, xmlrpcutil as _xmlrpc
 from cherrypy.lib import caching as _caching
 from cherrypy.lib import auth_basic, auth_digest
 
             # http://www.cherrypy.org/ticket/533
             # if a method is not found, an xmlrpclib.Fault should be returned
             # raising an exception here will do that; see
-            # cherrypy.lib.xmlrpc.on_error
+            # cherrypy.lib.xmlrpcutil.on_error
             raise Exception('method "%s" is not supported' % attr)
         
         conf = cherrypy.serving.request.toolmaps['tools'].get("xmlrpc", {})

py3/cherrypy/lib/xmlrpc.py

-import sys
-
-import cherrypy
-from cherrypy._cpcompat import ntob
-
-def process_body():
-    """Return (params, method) from request body."""
-    try:
-        # Python 3
-        from xmlrpc.client import loads
-    except ImportError:
-        # Python 2
-        from xmlrpclib import loads
-    
-    try:
-        return loads(cherrypy.request.body.read())
-    except Exception:
-        return ('ERROR PARAMS', ), 'ERRORMETHOD'
-
-
-def patched_path(path):
-    """Return 'path', doctored for RPC."""
-    if not path.endswith('/'):
-        path += '/'
-    if path.startswith('/RPC2/'):
-        # strip the first /rpc2
-        path = path[5:]
-    return path
-
-
-def _set_response(body):
-    # The XML-RPC spec (http://www.xmlrpc.com/spec) says:
-    # "Unless there's a lower-level error, always return 200 OK."
-    # Since Python's xmlrpclib interprets a non-200 response
-    # as a "Protocol Error", we'll just return 200 every time.
-    response = cherrypy.response
-    response.status = '200 OK'
-    response.body = ntob(body, 'utf-8')
-    response.headers['Content-Type'] = 'text/xml'
-    response.headers['Content-Length'] = len(body)
-
-
-def respond(body, encoding='utf-8', allow_none=0):
-    try:
-        # Python 2
-        from xmlrpclib import Fault, dumps
-    except ImportError:
-        # Python 3
-        from xmlrpc.client import Fault, dumps
-    if not isinstance(body, Fault):
-        body = (body,)
-    _set_response(dumps(body, methodresponse=1,
-                        encoding=encoding,
-                        allow_none=allow_none))
-
-def on_error(*args, **kwargs):
-    body = str(sys.exc_info()[1])
-    try:
-        # Python 2
-        from xmlrpclib import Fault, dumps
-    except ImportError:
-        # Python 3
-        from xmlrpc.client import Fault, dumps
-    _set_response(dumps(Fault(1, body)))
-

py3/cherrypy/lib/xmlrpcutil.py

+import sys
+
+import cherrypy
+from cherrypy._cpcompat import ntob
+
+def get_xmlrpclib():
+    try:
+        import xmlrpc.client as x
+    except ImportError:
+        import xmlrpclib as x
+    return x
+
+def process_body():
+    """Return (params, method) from request body."""
+    try:
+        return get_xmlrpclib().loads(cherrypy.request.body.read())
+    except Exception:
+        return ('ERROR PARAMS', ), 'ERRORMETHOD'
+
+
+def patched_path(path):
+    """Return 'path', doctored for RPC."""
+    if not path.endswith('/'):
+        path += '/'
+    if path.startswith('/RPC2/'):
+        # strip the first /rpc2
+        path = path[5:]
+    return path
+
+
+def _set_response(body):
+    # The XML-RPC spec (http://www.xmlrpc.com/spec) says:
+    # "Unless there's a lower-level error, always return 200 OK."
+    # Since Python's xmlrpclib interprets a non-200 response
+    # as a "Protocol Error", we'll just return 200 every time.
+    response = cherrypy.response
+    response.status = '200 OK'
+    response.body = ntob(body, 'utf-8')
+    response.headers['Content-Type'] = 'text/xml'
+    response.headers['Content-Length'] = len(body)
+
+
+def respond(body, encoding='utf-8', allow_none=0):
+    xmlrpclib = get_xmlrpclib()
+    if not isinstance(body, xmlrpclib.Fault):
+        body = (body,)
+    _set_response(xmlrpclib.dumps(body, methodresponse=1,
+                                  encoding=encoding,
+                                  allow_none=allow_none))
+
+def on_error(*args, **kwargs):
+    body = str(sys.exc_info()[1])
+    xmlrpclib = get_xmlrpclib()
+    _set_response(xmlrpclib.dumps(xmlrpclib.Fault(1, body)))
+

py3/cherrypy/test/test_xmlrpc.py

 import sys
-from xmlrpc.client import DateTime, Fault, ServerProxy, SafeTransport as HTTPSTransport
+from cherrypy._cpcompat import py3k
 
-# Python 3.0's SafeTransport still mistakenly checks for socket.ssl
-import socket
-if not hasattr(socket, "ssl"):
-    socket.ssl = True
+try:
+    from xmlrpclib import DateTime, Fault, ProtocolError, ServerProxy, SafeTransport
+except ImportError:
+    from xmlrpc.client import DateTime, Fault, ProtocolError, ServerProxy, SafeTransport
+
+if py3k:
+    HTTPSTransport = SafeTransport
+
+    # Python 3.0's SafeTransport still mistakenly checks for socket.ssl
+    import socket
+    if not hasattr(socket, "ssl"):
+        socket.ssl = True
+else:
+    class HTTPSTransport(SafeTransport):
+        """Subclass of SafeTransport to fix sock.recv errors (by using file)."""
+        
+        def request(self, host, handler, request_body, verbose=0):
+            # issue XML-RPC request
+            h = self.make_connection(host)
+            if verbose:
+                h.set_debuglevel(1)
+            
+            self.send_request(h, handler, request_body)
+            self.send_host(h, host)
+            self.send_user_agent(h)
+            self.send_content(h, request_body)
+            
+            errcode, errmsg, headers = h.getreply()
+            if errcode != 200:
+                raise ProtocolError(host + handler, errcode, errmsg, headers)
+            
+            self.verbose = verbose
+            
+            # Here's where we differ from the superclass. It says:
+            # try:
+            #     sock = h._conn.sock
+            # except AttributeError:
+            #     sock = None
+            # return self._parse_response(h.getfile(), sock)
+            
+            return self.parse_response(h.getfile())
 
 import cherrypy
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.