Debian Codegraph @

examples/xmlrpc_curl.py

raw
1 #! /usr/bin/env python
2 # vi:ts=4:et
3
4 # We should ignore SIGPIPE when using pycurl.NOSIGNAL - see
5 # the libcurl tutorial for more info.
6 try:
7 import signal
8 from signal import SIGPIPE, SIG_IGN
9 except ImportError:
10 pass
11 else:
12 signal.signal(SIGPIPE, SIG_IGN)
13
14 from io import StringIO
15 import xmlrpc.client as xmlrpclib
16 import pycurl
17 import sys
18
19
20 class CURLTransport(xmlrpclib.Transport):
21 """Handles a cURL HTTP transaction to an XML-RPC server."""
22
23 xmlrpc_h = [ "Content-Type: text/xml" ]
24
25 def __init__(self, username=None, password=None):
26 self.c = pycurl.Curl()
27 self.c.setopt(pycurl.POST, 1)
28 self.c.setopt(pycurl.NOSIGNAL, 1)
29 self.c.setopt(pycurl.CONNECTTIMEOUT, 30)
30 self.c.setopt(pycurl.HTTPHEADER, self.xmlrpc_h)
31 if username != None and password != None:
32 self.c.setopt(pycurl.USERPWD, '%s:%s' % (username, password))
33 self._use_datetime = False
34
35 def request(self, host, handler, request_body, verbose=0):
36 b = StringIO()
37 self.c.setopt(pycurl.URL, 'http://%s%s' % (host, handler))
38 self.c.setopt(pycurl.POSTFIELDS, request_body)
39 self.c.setopt(pycurl.WRITEFUNCTION, b.write)
40 self.c.setopt(pycurl.VERBOSE, verbose)
41 self.verbose = verbose
42 try:
43 self.c.perform()
44 except pycurl.error:
45 v = sys.exc_info()[1]
46 v = v.args
47 raise xmlrpclib.ProtocolError(
48 host + handler,
49 v[0], v[1], None
50 )
51 b.seek(0)
52 return self.parse_response(b)
53
54
55 if __name__ == "__main__":
56 ## Test
57 server = xmlrpclib.ServerProxy("http://betty.userland.com",
58 transport=CURLTransport())
59 print(server)
60 try:
61 print(server.examples.getStateName(41))
62 except xmlrpclib.Error:
63 v = sys.exc_info()[1]
64 print("ERROR", v)