Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a xml-rpc request in python?

Tags:

python

xml-rpc

I was just wondering, how would I be able to send a xml-rpc request in python? I know you can use xmlrpclib, but how do I send out a request in xml to access a function?

I would like to see the xml response.

So basically I would like to send the following as my request to the server:

<?xml version="1.0"?>
<methodCall>
  <methodName>print</methodName>
  <params>
    <param>
        <value><string>Hello World!</string></value>
    </param>
  </params>
</methodCall>

and get back the response

like image 530
John Jiang Avatar asked Feb 11 '10 03:02

John Jiang


2 Answers

Here's a simple XML-RPC client in Python:

import xmlrpclib

s = xmlrpclib.ServerProxy('http://localhost:8000')
print s.myfunction(2, 4)

Works with this server:

from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
                            requestHandler=RequestHandler)

def myfunction(x, y):
    status = 1
    result = [5, 6, [4, 5]]
    return (status, result)
server.register_function(myfunction)

# Run the server's main loop
server.serve_forever()

To access the guts of xmlrpclib, i.e. looking at the raw XML requests and so on, look up the xmlrpclib.Transport class in the documentation.

like image 155
Eli Bendersky Avatar answered Oct 06 '22 11:10

Eli Bendersky


I have pared down the source code in xmlrpc.client to a minimum required to send a xml rpc request (as I was interested in trying to port the functionality). It returns the response XML.

Server:

from xmlrpc.server import SimpleXMLRPCServer

def is_even(n):
    return n%2 == 0

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(is_even, "is_even")
server.serve_forever() 

Client:

import http.client

request_body = b"<?xml version='1.0'?>\n<methodCall>\n<methodName>is_even</methodName>\n<params>\n<param>\n<value><int>2</int></value>\n</param>\n</params>\n</methodCall>\n"

connection = http.client.HTTPConnection('localhost:8000')
connection.putrequest('POST', '/')
connection.putheader('Content-Type', 'text/xml')
connection.putheader('User-Agent', 'Python-xmlrpc/3.5')
connection.putheader("Content-Length", str(len(request_body)))
connection.endheaders(request_body)

print(connection.getresponse().read())
like image 27
Nicholas Clarke Avatar answered Oct 06 '22 10:10

Nicholas Clarke