Search code examples
pythonmultithreadingxml-rpcxmlrpclibsimplexmlrpcserver

XML-RPC returning value before executing all function code


I have XML-RPC server:

import time

import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer

class Worker(object):
    def start_work(self):
        # is it possible do return value to client here?
        self.do_work()
        return 'we started!'

    def do_work(self):
        while(True):
            print 'I\'m doing work...'
            time.sleep(3)


if __name__ == '__main__':
    port = 8080
    server = SimpleXMLRPCServer(("localhost", port))
    print "Listening on port %s..." % port

    w = Worker()

    server.register_function(w.start_work)
    while(1):
        server.handle_request()

# vim: filetype=python syntax=python expandtab shiftwidth=4 softtabstop=4 encoding=utf8

And easy client:

import xmlrpclib
c = xmlrpclib.ServerProxy('http://localhost:8080/')
print c.start_work()

Of course value returned by start_work function will be never printed.

My question is how to rewrite server code to make possible returning value before finishing work. I know that I can use threads for that but I want to be sure that there is no easier way.


Solution

  • If you want XML-RPC with long-running, early returning tasks, you probably need to rewrite your server into an asynchronous framework, like twisted