Monday, June 30, 2008

Sending Binary files over xml rpc

I'm posting this because I finally figured how to send files(pictures in particular) over xmlrpc. It took me a while to figure it out since I was mostly concerned with saving the files into database but here it is.

#!/usr/bin/env python

from twisted.web import xmlrpc, server
import os

class PositRPC(xmlrpc.XMLRPC):
        def xmlrpc_savefile(self, file):
                datum =
                thefile = open('/tmp/gnu.jpg', "wb")
                #filebuffer = file
                #os.spawnl(os.P_NOWAIT, '/usr/bin/display', '/tmp/gnu.jpg')  
                print datum
                return 1

if __name__ == '__main__':
    from twisted.internet import reactor
    r = PositRPC()
    reactor.listenTCP(7080, server.Site(r))

Then I opened trusty IDLE
>>> import xmlrpclib
>>> s = xmlrpclib.Server('')
>>> d = xmlrpclib.Binary(open('/home/pras/PicasaDocuments/gnu.jpg', 'rb'))
>>> s.savefile(d)

The idea here is that although the file is sent as a Binary, we need to convert it to string(bytes) to save it. Since we have opened the file with 'rb' option in IDLE and with 'wb' option in our server (respectively for read binary and write binary), we get binary file at the server end.


Duncan McGreggor said...

Nicely done, Prasanna :-) I added this post to the latest "Twisted in the News" article at our Labs blog.