Exercise 11.1

Objectives:

  • A small taste of network programming in Python.

  • Build an XML-RPC server that implements a simple key-value store

Files Created: kvstore.py

Files Modified: None

(a) Creating an XML-RPC server

XML-RPC makes it easy to build programs where you can carry out various operations remotely. In this exercise,we’ll build a server that operates as a simple key-value store.

First, create a file kvstore.py that contains the following code:

# kvstore.py
#
# A simple key-value store using XML-RPC

# Internal dictionary that stores the actual data
_store = {}

# Functions that save, load, and delete contents
def save(key,value):
    _store[key] = value

def load(key):
    return _store.get(key,None)

def delete(key):
    if key in _store:
        del _store[key]

if __name__ == '__main__':
    from SimpleXMLRPCServer import SimpleXMLRPCServer
    serv = SimpleXMLRPCServer(("",15000),allow_none=True)
    serv.register_function(save)
    serv.register_function(load)
    serv.register_function(delete)
    serv.serve_forever()

Study this code carefully. It defines three functions; save() which stores an item in a dictionary, load() which returns the contents of an item, and delete() which deletes an item.

In a separate terminal window (not IDLE), run the above program. It’s not going to do anything until we connect to it and start issuing commands. See the next part.

(b) Interacting with the XML-RPC server

Now, in IDLE or a separate terminal window, launch Python and connect to the server you just launched.

>>> from xmlrpclib import ServerProxy
>>> s = ServerProxy("http://localhost:15000")
>>>

Now, start executing some commands:

>>> s.save("name","Guido")
>>> s.save("nameserver","8.8.8.8")
>>> s.save("ports", [4050,5100,5200])
>>>

In yet another terminal window, launch Python and type these statements:

>>> from xmlrpclib import ServerProxy
>>> s = ServerProxy("http://localhost:15000")
>>> s.load("name")
'Guido'
>>> s.load("nameserver")
'8.8.8.8.8'
>>> s.load("ports")
[4050, 5100, 5200]
>>>

Now, why would you want to have such a key-value server? In a distributed system, you could use such a server to collect commonly shared data such as configuration parameters, machine status, or other details. You could even build a simple in-memory database. More sophisticated key-value stores are also the basis of so-called "NoSQL" databases.

SPECIAL TOPIC: Advanced Networks. This section covers some additional network-related topics including advanced uses of urllib and information on how to use SSL.

Links