Question

I am new to XML-RPC.

#client code
import xmlrpclib
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
x,y = arg1,arg2
print proxy.fun1(x,y)
print proxy.fun2(x,y)

What server should do:

  1. load fun1
  2. register fun1
  3. return result
  4. unload fun1

and then do same with fun2.

What is the best way to do this?

I have figured out a way to do this but it sounds "clumsy,far fetched and unpythonic".

Was it helpful?

Solution

If you want dynamic registering, register an instance of an object, and then set attributes on that object. You can get more advanced by using the __getattr__ method of the class if the function needs to be determined at run time.

class dispatcher(object): pass
   def __getattr__(self, name):
     # logic to determine if 'name' is a function, and what
     # function should be returned
     return the_func
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_instance(dispatcher())

OTHER TIPS

Generally the server keeps on running - so register both methods at the start. I don't understand why you want to unregister your functions. Servers stay up and handle multiple requests. You might possible want a shutdown() function that shuts the entire server down, but I don't see anyway to unregister a single function.

The easiest way is with SimpleXMLRPCServer:

from SimpleXMLRPCServer import SimpleXMLRPCServer

def fun1(x, y):
    return x + y


def fun2(x, y):
    return x - y

server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(fun1)
server.register_function(fun2)
server.serve_forever()

You can register functions dynamically (after the server has been started):

#Server side code:
import sys
from SimpleXMLRPCServer import SimpleXMLRPCServer

def dynRegFunc(): #this function will be registered dynamically, from the client
     return True 

def registerFunction(function): #this function will register with the given name
    server.register_function(getattr(sys.modules[__name__], str(function)))

if __name__ == '__main__':
    server = SimpleXMLRPCServer((address, port)), allow_none = True)
    server.register_function(registerFunction)
    server.serve_forever()



#Client side code:

 import xmlrpclib

 if __name__ == '__main__':
     proxy = xmlrpclib.ServerProxy('http://'+str(address)+':'+str(port), allow_none = True)

 #if you'd try to call the function dynRegFunc now, it wouldnt work, since it's not registered -> proxy.dynRegFunc() would fail to execute

 #register function dynamically: 
  proxy.registerFunction("dynRegFunc")
 #call the newly registered function
  proxy.dynRegFunc() #should work now!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top