diff -r 52ab9e1ff46a Doc/library/xmlrpc.client.rst --- a/Doc/library/xmlrpc.client.rst Sun Feb 16 14:17:28 2014 -0500 +++ b/Doc/library/xmlrpc.client.rst Sun Feb 16 22:40:48 2014 +0200 @@ -191,6 +191,11 @@ no such string is available, an empty string is returned. The documentation string may contain HTML markup. +.. versionadded:: 3.5 + + The :class:`ServerProxy` can be used as a context manager in + the :keyword:`with` statement to close the underlying transport. + A working example follows. The server code:: @@ -208,9 +213,9 @@ import xmlrpc.client - proxy = xmlrpc.client.ServerProxy("http://localhost:8000/") - print("3 is even: %s" % str(proxy.is_even(3))) - print("100 is even: %s" % str(proxy.is_even(100))) + with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy: + print("3 is even: %s" % str(proxy.is_even(3))) + print("100 is even: %s" % str(proxy.is_even(100))) .. _datetime-objects: @@ -518,14 +523,14 @@ from xmlrpc.client import ServerProxy, Error # server = ServerProxy("http://localhost:8000") # local server - server = ServerProxy("http://betty.userland.com") + with ServerProxy("http://betty.userland.com") as server: - print(server) + print(server) - try: - print(server.examples.getStateName(41)) - except Error as v: - print("ERROR", v) + try: + print(server.examples.getStateName(41)) + except Error as v: + print("ERROR", v) To access an XML-RPC server through a proxy, you need to define a custom transport. The following example shows how: diff -r 52ab9e1ff46a Lib/test/test_xmlrpc.py --- a/Lib/test/test_xmlrpc.py Sun Feb 16 14:17:28 2014 -0500 +++ b/Lib/test/test_xmlrpc.py Sun Feb 16 22:40:48 2014 +0200 @@ -713,7 +713,14 @@ conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye') conn.close() - + def test_context_manager(self): + with xmlrpclib.ServerProxy(URL) as server: + server.add(2, 3) + self.assertNotEqual(server('transport')._connection, + (None, None)) + self.assertEqual(server('transport')._connection, + (None, None)) + class MultiPathServerTestCase(BaseServerTestCase): threadFunc = staticmethod(http_multi_server) request_count = 2 @@ -898,6 +905,7 @@ p = xmlrpclib.ServerProxy(self.url, transport=t) self.assertEqual(p('transport'), t) + # This is a contrived way to make a failure occur on the server side # in order to test the _send_traceback_header flag on the server class FailingMessageClass(http.client.HTTPMessage): diff -r 52ab9e1ff46a Lib/xmlrpc/client.py --- a/Lib/xmlrpc/client.py Sun Feb 16 14:17:28 2014 -0500 +++ b/Lib/xmlrpc/client.py Sun Feb 16 22:40:48 2014 +0200 @@ -1450,6 +1450,12 @@ return self.__transport raise AttributeError("Attribute %r not found" % (attr,)) + def __enter__(self): + return self + + def __exit__(self, *args): + self.__close() + # compatibility Server = ServerProxy