Welcome, guest | Sign In | My Account | Store | Cart

SimpleXMLRPCServer is too simple. It's serve_forever function doesn't allow it to be incorporated into anything that needs to be gracefully stopped at some point. This code extends SimpleXMLRPCServer with the server_until_stopped and stop_serving functions.

Python, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import socket
from select import select
from SimpleXMLRPCServer import SimpleXMLRPCServer

class XMLRPCServer(SimpleXMLRPCServer):
    """
    A variant of SimpleXMLRPCServer that can be stopped.
    """
    def __init__(self, *args, **kwargs):
        SimpleXMLRPCServer.__init__(self, *args, **kwargs)
        self.logRequests = 0
        self.closed = False
    
    def serve_until_stopped(self):
        self.socket.setblocking(0)
        while not self.closed:
            self.handle_request()        
            
    def stop_serving(self):
        self.closed = True
    
    def get_request(self):
        inputObjects = []
        while not inputObjects and not self.closed:
            inputObjects, outputObjects, errorObjects = \
                select([self.socket], [], [], 0.2)
            try:
                return self.socket.accept()
            except socket.error:
                raise

I usually run this code in a separate thread thread and do a stop_serving and a join on the thread when the application is about to exit.