Ir al contenido principal

Ralsina.Me — El sitio web de Roberto Alsina

Nifty python/xmlrpc thing

Us­ing python, it's triv­ial to turn any mod­ule in­to a XML­R­PC serv­er. So, if you are care­ful writ­ing your app in a mod­u­lar way, you can move the back­end else­where in very lit­tle code.

For ex­am­ple, if I had a mod­ule that has some func­tion­al­i­ty, like this (mod­

#Stupid simple module

def  add(a,b):
        return a+b

A pro­gram would use it like this:

import module
print module.add(2,4)

Now, if I move the mod­ule to a re­mote box (server), cre­ate this xml­r­pc serv­er pro­gram in the serv­er (and run it ;-):

#!/usr/bin/env python

#Simple generic XML-RPC server

import module

import SimpleXMLRPCServer

server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 800


And this bridge mod­ule in the client (client­mod­

import xmlrpclib

server = xmlrpclib.Server('')

Now this very slight­ly mod­i­fied ver­sion of our pro­gram works in ex­act­ly the same way as the orig­i­nal:

from clientmodule import server as module

print module.add(2,4)

Of course this has is­sues:

  • It has no se­cu­ri­ty
  • XML­R­PC could in­tro­duce er­rors and the pro­gram does­n't catch them.
  • It could be made even more trans­par­ent with some more python­ing

But any­way, I think it's cute.

Contents © 2000-2023 Roberto Alsina