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.

Adams Kevin said...

I ADAMS KEVIN, a representative of Aiico Insurance plc, we trust and respect for individual differences in day out a loan. We will provide 2% of the loan's interest rate. If you are interested in this business contact us by e-mail ( now transfer their loan documents issued properly. Do you need a loan to set up business or school if you are very welcom to aiico insurance can also contact us by email( we first week can request a balance transfer.

व्यक्तिगत व्यवसायका लागि ऋण चाहिन्छ? तपाईं आफ्नो इमेल संपर्क भने उपरोक्त तुरुन्तै आफ्नो ऋण स्थानान्तरण प्रक्रिया गर्न