f8d33b2fb05d7e5bdf1cf24572fa1595bb486be9
[quix0rs-apt-p2p.git] / xmlrpcclient.py
1 from twisted.internet.protocol import ClientFactory
2 from twisted.protocols.http import HTTPClient
3 from twisted.internet.defer import Deferred
4
5 from xmlrpclib import loads, dumps
6 import socket
7
8 USER_AGENT = 'Python/Twisted XMLRPC 0.1'
9 class XMLRPCClient(HTTPClient):
10     def connectionMade(self):
11         payload = dumps(self.args, self.method)
12         self.sendCommand('POST', '/RPC2')
13         self.sendHeader('User-Agent', USER_AGENT)
14         self.sendHeader('Content-Type', 'text/xml')
15         self.sendHeader('Content-Length', len(payload))
16         self.endHeaders()
17         self.transport.write(payload)
18         self.transport.write('\r\n')
19         
20     def handleResponse(self, buf):
21         try:
22             args, name = loads(buf)
23         except Exception, e:
24             print "response decode error: " + `e`
25             self.d.errback()
26         else:
27             apply(self.d.callback, args)
28
29 class XMLRPCClientFactory(ClientFactory):
30     def __init__(self, method, args, callback=None, errback=None):
31         self.method = method
32         self.args = args
33         self.d = Deferred()
34         if callback:
35             self.d.addCallback(callback)
36         if errback:
37             self.d.addErrback(errback)
38         self.noisy = 0
39         
40     def buildProtocol(self, addr):
41         prot =  XMLRPCClient()
42         prot.method = self.method
43         prot.args = self.args
44         prot.d = self.d
45         return prot
46
47     def clientConnectionFailed(self, connector, reason):
48         self.d.errback()