Sunday, September 1, 2013

XML-RPC Client/Server in Python

This demo shows how to have RPC connection in python.  The server collects CPU information (Linux).

Server-side:

 #!/usr/bin/python
import re
import os
import sys
import xmlrpclib

from SimpleXMLRPCServer import SimpleXMLRPCServer

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

def get_mhz():
    try:
        #return 0
        f = open("/proc/cpuinfo", 'r')
    except IOError:
        print "Unable to access /proc/cpuinfo"
        exit
    except:
        print "Other unhandled error (why?)"
      
    else:
        f.seek(0)
        line = f.readline()
        while line:
            line = line.strip()
            print "line = %s" % line
            m = re.match("cpu MHz[\t ]+: (.*)", line)
            if m:
                print m.group(1)
                f.close()
                return m.group(1)
            line = f.readline()
      
#    finally:
#        print "Sorry, still fails"


def xmlsrv_exit():
    print "trying to exit now..."
    try:
        print "try sys.exit(0)"
        #sys.exit(0)
    except:
        print "Unable to exit"
  
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "xmlsrv_is_even")
server.register_function(get_mhz, "xmlsrv_get_mhz")
server.register_function(xmlsrv_exit, "xmlsrv_exit")
server.serve_forever()





Client side:

#!/usr/bin/python

import xmlrpclib

try:
    proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
    #print proxy.system.listMethods()
    print "3 is even: %s" % str(proxy.xmlsrv_is_even(3))
    print "100 is even: %s" % str(proxy.xmlsrv_is_even(100))

    print "CPU Clock: %s" % str(proxy.xmlsrv_get_mhz())

except xmlrpclib.Fault, err:
    print "A fault occurred"
    print "Fault code: %d" % err.faultCode
    print "Fault string: %s" % err.faultString
   
#proxy.xmlsrv_exit()


 

No comments:

Post a Comment