November 15, 2008

Python Web Services - HOW TO 2 - XML-RPC Server

It’s possible to write web services with Python in too many ways i said in Python Web Services HOW TO-1 (ZSI) and i explain how to write a web service by using ZSI framework. Now i want to explain how to write the same web service by using XML-RPC Server.

It's a lot easier to write web service by using XML-RPC Server than by using ZSI framework. You just need this Python XmlRpcServer Module and an Apache Web Server. Why don't we start then;

First we write down our web service implementation in Python;

We import the sys and XmlRpcServer modules first.

#!/usr/bin/env python

import sys

from xmlrpcserver import XmlRpcServer

Then we write down what the response contains it's data as.

sys.stdout.write("Content-type: text/xml\n\n")

And we write down our web service implementation.

def sillyfunction(self, param):

return param

At the end we create a server from our XmlRpcServer module, register it to our function and run the server as an Apache cgi code.

server = XmlRpcServer()

server.register("asillyfunction", sillyfunction)

server.execute()

To run the code as cgi, we just copy our code to the place where Apache server runs cgi codes. It is /usr/lib/cgi-bin in my linux distribution. Also you can define this place in your Apache server configuration as you want and also you can give ssl support within this configuration files too. Just for now i assume our cgi directory is /usr/lib/cgi-bin/ and we saved our code as silly.py;

cp silly.py /usr/lib/cgi-bin/

Also we may copy the XmlRpcServer code to same place or we just use system module and append the path that contains this file in our python code. In this case i just copy this file to there too.

cp xmlrpcserver.py /usr/lib/cgi-bin/

Then we just change the ownership of files to 755 for Apache to run the codes.

cd /usr/lib/cgi-bin/

chmod 755 silly.py xmlrpcserver.py

And that's it, we have a Python Xml-Rpc Server that runs under our Apache Web Server now.

Here is the sample code. And here is how to write a client that connects to this web service with XML-RPC and say hello to it.


No comments: