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

Just thought I'd share a few xmlrpc server niceties. - Simple (and not very secure) access controll - Port rebinding (If you code anything like me, this comes in handy) - register_instance with class

Python, 39 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
31
32
33
34
35
36
37
38
39
import SimpleXMLRPCServer
import string,socket

accessList=(
    '127.0.0.1',
    '192.168.0.15'
    )

class Server(SimpleXMLRPCServer.SimpleXMLRPCServer):
    def __init__(self,*args):
        SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self,(args[0],args[1]))
        
    def server_bind(self):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        SimpleXMLRPCServer.SimpleXMLRPCServer.server_bind(self)

    def verify_request(self,request, client_address):
        if client_address[0] in accessList:
            return 1
        else:
            return 0
        
class xmlrpc_registers:
    def __init__(self):
        self.python_string = string
        
    def add(self, x, y):
        return x + y

    def mult(self,x,y):
        return x*y

    def div(self,x,y):
        return x//y

if __name__ == "__main__":
    server = Server('',8000)
    server.register_instance(xmlrpc_registers())
    server.serve_forever()

3 comments

Jeff Bauer 21 years, 2 months ago  # | flag

SimpleXMLRPCServer.SimpleXMLRPCServer. One simplification. If you replace change the import statement to:

from SimpleXMLRPCServer import SimpleXMLRPCServer

Every "SimpleXMLRPCServer.SimpleXMLRPCServer" can be replaced with just "SimpleXMLRPCServer".

David Ascher 19 years, 1 month ago  # | flag

CAUTION: Security advisory affects this code. As discussed in

http://www.python.org/security/PSF-2005-001/

There is a new known vulnerability in the standard XML-RPC library in Python 2.2 and later.

Patches are available off of that URL, and new ActivePython builds or instructions on how to fix existing installations will be available shortly. (Python.org folks are also planning on providing updated builds).

-- David Ascher

dirk janssen 17 years, 5 months ago  # | flag

Another small nicety on the client side. Before you start any client or create a proxy, instruct the socket module to produce timeouts when connection is taking too long. Without this, your rpc call can hang indefinitely.

socket.setdefaulttimeout(60)

This is a time out in seconds, after which you will get a socket.error. You can easily catch this error and decide to try again, but at least your program will not hang forever.