1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
|
<span id="xmlrpc-client-xml-rpc-client-access"></span><h1>xmlrpc.client — XML-RPC client access</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/xmlrpc/client.py">Lib/xmlrpc/client.py</a></p> <p>XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data. This module supports writing XML-RPC client code; it handles all the details of translating between conformable Python objects and XML on the wire.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>The <a class="reference internal" href="#module-xmlrpc.client" title="xmlrpc.client: XML-RPC client access."><code>xmlrpc.client</code></a> module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see <a class="reference internal" href="xml#xml-vulnerabilities"><span class="std std-ref">XML vulnerabilities</span></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>For HTTPS URIs, <a class="reference internal" href="#module-xmlrpc.client" title="xmlrpc.client: XML-RPC client access."><code>xmlrpc.client</code></a> now performs all the necessary certificate and hostname checks by default.</p> </div> <div class="availability docutils container"> <p><a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#availability"><span class="std std-ref">Availability</span></a>: not Emscripten, not WASI.</p> <p>This module does not work or is not available on WebAssembly platforms <code>wasm32-emscripten</code> and <code>wasm32-wasi</code>. See <a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#wasm-availability"><span class="std std-ref">WebAssembly platforms</span></a> for more information.</p> </div> <dl class="py class"> <dt class="sig sig-object py" id="xmlrpc.client.ServerProxy">
<code>class xmlrpc.client.ServerProxy(uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, headers=(), context=None)</code> </dt> <dd>
<p>A <a class="reference internal" href="#xmlrpc.client.ServerProxy" title="xmlrpc.client.ServerProxy"><code>ServerProxy</code></a> instance is an object that manages communication with a remote XML-RPC server. The required first argument is a URI (Uniform Resource Indicator), and will normally be the URL of the server. The optional second argument is a transport factory instance; by default it is an internal <code>SafeTransport</code> instance for https: URLs and an internal HTTP <code>Transport</code> instance otherwise. The optional third argument is an encoding, by default UTF-8. The optional fourth argument is a debugging flag.</p> <p>The following parameters govern the use of the returned proxy instance. If <em>allow_none</em> is true, the Python constant <code>None</code> will be translated into XML; the default behaviour is for <code>None</code> to raise a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>. This is a commonly used extension to the XML-RPC specification, but isn’t supported by all clients and servers; see <a class="reference external" href="https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php">http://ontosys.com/xml-rpc/extensions.php</a> for a description. The <em>use_builtin_types</em> flag can be used to cause date/time values to be presented as <a class="reference internal" href="datetime#datetime.datetime" title="datetime.datetime"><code>datetime.datetime</code></a> objects and binary data to be presented as <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> objects; this flag is false by default. <a class="reference internal" href="datetime#datetime.datetime" title="datetime.datetime"><code>datetime.datetime</code></a>, <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> and <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> objects may be passed to calls. The <em>headers</em> parameter is an optional sequence of HTTP headers to send with each request, expressed as a sequence of 2-tuples representing the header name and value. (e.g. <code>[('Header-Name', 'value')]</code>). The obsolete <em>use_datetime</em> flag is similar to <em>use_builtin_types</em> but it applies only to date/time values.</p> </dd>
</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>The <em>use_builtin_types</em> flag was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>headers</em> parameter was added.</p> <p>Both the HTTP and HTTPS transports support the URL syntax extension for HTTP Basic Authentication: <code>http://user:pass@host:port/path</code>. The <code>user:pass</code> portion will be base64-encoded as an HTTP ‘Authorization’ header, and sent to the remote server as part of the connection process when invoking an XML-RPC method. You only need to use this if the remote server requires a Basic Authentication user and password. If an HTTPS URL is provided, <em>context</em> may be <a class="reference internal" href="ssl#ssl.SSLContext" title="ssl.SSLContext"><code>ssl.SSLContext</code></a> and configures the SSL settings of the underlying HTTPS connection.</p> <p>The returned instance is a proxy object with methods that can be used to invoke corresponding RPC calls on the remote server. If the remote server supports the introspection API, the proxy can also be used to query the remote server for the methods it supports (service discovery) and fetch other server-associated metadata.</p> <p>Types that are conformable (e.g. that can be marshalled through XML), include the following (and except where noted, they are unmarshalled as the same Python type):</p> <table class="docutils align-default"> <thead> <tr>
<th class="head"><p>XML-RPC type</p></th> <th class="head"><p>Python type</p></th> </tr> </thead> <tr>
<td><p><code>boolean</code></p></td> <td><p><a class="reference internal" href="functions#bool" title="bool"><code>bool</code></a></p></td> </tr> <tr>
<td><p><code>int</code>, <code>i1</code>, <code>i2</code>, <code>i4</code>, <code>i8</code> or <code>biginteger</code></p></td> <td><p><a class="reference internal" href="functions#int" title="int"><code>int</code></a> in range from -2147483648 to 2147483647. Values get the <code><int></code> tag.</p></td> </tr> <tr>
<td><p><code>double</code> or <code>float</code></p></td> <td><p><a class="reference internal" href="functions#float" title="float"><code>float</code></a>. Values get the <code><double></code> tag.</p></td> </tr> <tr>
<td><p><code>string</code></p></td> <td><p><a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a></p></td> </tr> <tr>
<td><p><code>array</code></p></td> <td><p><a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> or <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> containing conformable elements. Arrays are returned as <a class="reference internal" href="stdtypes#list" title="list"><code>lists</code></a>.</p></td> </tr> <tr>
<td><p><code>struct</code></p></td> <td><p><a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>. Keys must be strings, values may be any conformable type. Objects of user-defined classes can be passed in; only their <a class="reference internal" href="stdtypes#object.__dict__" title="object.__dict__"><code>__dict__</code></a> attribute is transmitted.</p></td> </tr> <tr>
<td><p><code>dateTime.iso8601</code></p></td> <td><p><a class="reference internal" href="#xmlrpc.client.DateTime" title="xmlrpc.client.DateTime"><code>DateTime</code></a> or <a class="reference internal" href="datetime#datetime.datetime" title="datetime.datetime"><code>datetime.datetime</code></a>. Returned type depends on values of <em>use_builtin_types</em> and <em>use_datetime</em> flags.</p></td> </tr> <tr>
<td><p><code>base64</code></p></td> <td><p><a class="reference internal" href="#xmlrpc.client.Binary" title="xmlrpc.client.Binary"><code>Binary</code></a>, <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> or <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a>. Returned type depends on the value of the <em>use_builtin_types</em> flag.</p></td> </tr> <tr>
<td><p><code>nil</code></p></td> <td><p>The <code>None</code> constant. Passing is allowed only if <em>allow_none</em> is true.</p></td> </tr> <tr>
<td><p><code>bigdecimal</code></p></td> <td><p><a class="reference internal" href="decimal#decimal.Decimal" title="decimal.Decimal"><code>decimal.Decimal</code></a>. Returned type only.</p></td> </tr> </table> <p>This is the full set of data types supported by XML-RPC. Method calls may also raise a special <a class="reference internal" href="#xmlrpc.client.Fault" title="xmlrpc.client.Fault"><code>Fault</code></a> instance, used to signal XML-RPC server errors, or <a class="reference internal" href="#xmlrpc.client.ProtocolError" title="xmlrpc.client.ProtocolError"><code>ProtocolError</code></a> used to signal an error in the HTTP/HTTPS transport layer. Both <a class="reference internal" href="#xmlrpc.client.Fault" title="xmlrpc.client.Fault"><code>Fault</code></a> and <a class="reference internal" href="#xmlrpc.client.ProtocolError" title="xmlrpc.client.ProtocolError"><code>ProtocolError</code></a> derive from a base class called <code>Error</code>. Note that the xmlrpc client module currently does not marshal instances of subclasses of built-in types.</p> <p>When passing strings, characters special to XML such as <code><</code>, <code>></code>, and <code>&</code> will be automatically escaped. However, it’s the caller’s responsibility to ensure that the string is free of characters that aren’t allowed in XML, such as the control characters with ASCII values between 0 and 31 (except, of course, tab, newline and carriage return); failing to do this will result in an XML-RPC request that isn’t well-formed XML. If you have to pass arbitrary bytes via XML-RPC, use <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> or <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> classes or the <a class="reference internal" href="#xmlrpc.client.Binary" title="xmlrpc.client.Binary"><code>Binary</code></a> wrapper class described below.</p> <p><code>Server</code> is retained as an alias for <a class="reference internal" href="#xmlrpc.client.ServerProxy" title="xmlrpc.client.ServerProxy"><code>ServerProxy</code></a> for backwards compatibility. New code should use <a class="reference internal" href="#xmlrpc.client.ServerProxy" title="xmlrpc.client.ServerProxy"><code>ServerProxy</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Added the <em>context</em> argument.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Added support of type tags with prefixes (e.g. <code>ex:nil</code>). Added support of unmarshalling additional types used by Apache XML-RPC implementation for numerics: <code>i1</code>, <code>i2</code>, <code>i8</code>, <code>biginteger</code>, <code>float</code> and <code>bigdecimal</code>. See <a class="reference external" href="https://ws.apache.org/xmlrpc/types.html">https://ws.apache.org/xmlrpc/types.html</a> for a description.</p> </div> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference external" href="https://tldp.org/HOWTO/XML-RPC-HOWTO/index.html">XML-RPC HOWTO</a></dt>
<dd>
<p>A good description of XML-RPC operation and client software in several languages. Contains pretty much everything an XML-RPC client developer needs to know.</p> </dd> <dt><a class="reference external" href="https://xmlrpc-c.sourceforge.net/introspection.html">XML-RPC Introspection</a></dt>
<dd>
<p>Describes the XML-RPC protocol extension for introspection.</p> </dd> <dt><a class="reference external" href="http://xmlrpc.scripting.com/spec.html">XML-RPC Specification</a></dt>
<dd>
<p>The official specification.</p> </dd> </dl> </div> <section id="serverproxy-objects"> <span id="id1"></span><h2>ServerProxy Objects</h2> <p>A <a class="reference internal" href="#xmlrpc.client.ServerProxy" title="xmlrpc.client.ServerProxy"><code>ServerProxy</code></a> instance has a method corresponding to each remote procedure call accepted by the XML-RPC server. Calling the method performs an RPC, dispatched by both name and argument signature (e.g. the same method name can be overloaded with multiple argument signatures). The RPC finishes by returning a value, which may be either returned data in a conformant type or a <a class="reference internal" href="#xmlrpc.client.Fault" title="xmlrpc.client.Fault"><code>Fault</code></a> or <a class="reference internal" href="#xmlrpc.client.ProtocolError" title="xmlrpc.client.ProtocolError"><code>ProtocolError</code></a> object indicating an error.</p> <p>Servers that support the XML introspection API support some common methods grouped under the reserved <code>system</code> attribute:</p> <dl class="py method"> <dt class="sig sig-object py" id="xmlrpc.client.ServerProxy.system.listMethods">
<code>ServerProxy.system.listMethods()</code> </dt> <dd>
<p>This method returns a list of strings, one for each (non-system) method supported by the XML-RPC server.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="xmlrpc.client.ServerProxy.system.methodSignature">
<code>ServerProxy.system.methodSignature(name)</code> </dt> <dd>
<p>This method takes one parameter, the name of a method implemented by the XML-RPC server. It returns an array of possible signatures for this method. A signature is an array of types. The first of these types is the return type of the method, the rest are parameters.</p> <p>Because multiple signatures (ie. overloading) is permitted, this method returns a list of signatures rather than a singleton.</p> <p>Signatures themselves are restricted to the top level parameters expected by a method. For instance if a method expects one array of structs as a parameter, and it returns a string, its signature is simply “string, array”. If it expects three integers and returns a string, its signature is “string, int, int, int”.</p> <p>If no signature is defined for the method, a non-array value is returned. In Python this means that the type of the returned value will be something other than list.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="xmlrpc.client.ServerProxy.system.methodHelp">
<code>ServerProxy.system.methodHelp(name)</code> </dt> <dd>
<p>This method takes one parameter, the name of a method implemented by the XML-RPC server. It returns a documentation string describing the use of that method. If no such string is available, an empty string is returned. The documentation string may contain HTML markup.</p> </dd>
</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Instances of <a class="reference internal" href="#xmlrpc.client.ServerProxy" title="xmlrpc.client.ServerProxy"><code>ServerProxy</code></a> support the <a class="reference internal" href="../glossary#term-context-manager"><span class="xref std std-term">context manager</span></a> protocol for closing the underlying transport.</p> </div> <p>A working example follows. The server code:</p> <pre data-language="python">from xmlrpc.server import SimpleXMLRPCServer
def is_even(n):
return n % 2 == 0
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(is_even, "is_even")
server.serve_forever()
</pre> <p>The client code for the preceding server:</p> <pre data-language="python">import xmlrpc.client
with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy:
print("3 is even: %s" % str(proxy.is_even(3)))
print("100 is even: %s" % str(proxy.is_even(100)))
</pre> </section> <section id="datetime-objects"> <span id="id2"></span><h2>DateTime Objects</h2> <dl class="py class"> <dt class="sig sig-object py" id="xmlrpc.client.DateTime">
<code>class xmlrpc.client.DateTime</code> </dt> <dd>
<p>This class may be initialized with seconds since the epoch, a time tuple, an ISO 8601 time/date string, or a <a class="reference internal" href="datetime#datetime.datetime" title="datetime.datetime"><code>datetime.datetime</code></a> instance. It has the following methods, supported mainly for internal use by the marshalling/unmarshalling code:</p> <dl class="py method"> <dt class="sig sig-object py" id="xmlrpc.client.DateTime.decode">
<code>decode(string)</code> </dt> <dd>
<p>Accept a string as the instance’s new time value.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="xmlrpc.client.DateTime.encode">
<code>encode(out)</code> </dt> <dd>
<p>Write the XML-RPC encoding of this <a class="reference internal" href="#xmlrpc.client.DateTime" title="xmlrpc.client.DateTime"><code>DateTime</code></a> item to the <em>out</em> stream object.</p> </dd>
</dl> <p>It also supports certain of Python’s built-in operators through <a class="reference internal" href="../reference/datamodel#object.__lt__" title="object.__lt__"><code>rich comparison</code></a> and <a class="reference internal" href="../reference/datamodel#object.__repr__" title="object.__repr__"><code>__repr__()</code></a> methods.</p> </dd>
</dl> <p>A working example follows. The server code:</p> <pre data-language="python">import datetime
from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client
def today():
today = datetime.datetime.today()
return xmlrpc.client.DateTime(today)
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(today, "today")
server.serve_forever()
</pre> <p>The client code for the preceding server:</p> <pre data-language="python">import xmlrpc.client
import datetime
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
today = proxy.today()
# convert the ISO8601 string to a datetime object
converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
</pre> </section> <section id="binary-objects"> <span id="id3"></span><h2>Binary Objects</h2> <dl class="py class"> <dt class="sig sig-object py" id="xmlrpc.client.Binary">
<code>class xmlrpc.client.Binary</code> </dt> <dd>
<p>This class may be initialized from bytes data (which may include NULs). The primary access to the content of a <a class="reference internal" href="#xmlrpc.client.Binary" title="xmlrpc.client.Binary"><code>Binary</code></a> object is provided by an attribute:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="xmlrpc.client.Binary.data">
<code>data</code> </dt> <dd>
<p>The binary data encapsulated by the <a class="reference internal" href="#xmlrpc.client.Binary" title="xmlrpc.client.Binary"><code>Binary</code></a> instance. The data is provided as a <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> object.</p> </dd>
</dl> <p><a class="reference internal" href="#xmlrpc.client.Binary" title="xmlrpc.client.Binary"><code>Binary</code></a> objects have the following methods, supported mainly for internal use by the marshalling/unmarshalling code:</p> <dl class="py method"> <dt class="sig sig-object py" id="xmlrpc.client.Binary.decode">
<code>decode(bytes)</code> </dt> <dd>
<p>Accept a base64 <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> object and decode it as the instance’s new data.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="xmlrpc.client.Binary.encode">
<code>encode(out)</code> </dt> <dd>
<p>Write the XML-RPC base 64 encoding of this binary item to the <em>out</em> stream object.</p> <p>The encoded data will have newlines every 76 characters as per <span class="target" id="index-0"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2045.html#section-6.8"><strong>RFC 2045 section 6.8</strong></a>, which was the de facto standard base64 specification when the XML-RPC spec was written.</p> </dd>
</dl> <p>It also supports certain of Python’s built-in operators through <a class="reference internal" href="../reference/datamodel#object.__eq__" title="object.__eq__"><code>__eq__()</code></a> and <a class="reference internal" href="../reference/datamodel#object.__ne__" title="object.__ne__"><code>__ne__()</code></a> methods.</p> </dd>
</dl> <p>Example usage of the binary objects. We’re going to transfer an image over XMLRPC:</p> <pre data-language="python">from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client
def python_logo():
with open("python_logo.jpg", "rb") as handle:
return xmlrpc.client.Binary(handle.read())
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(python_logo, 'python_logo')
server.serve_forever()
</pre> <p>The client gets the image and saves it to a file:</p> <pre data-language="python">import xmlrpc.client
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
with open("fetched_python_logo.jpg", "wb") as handle:
handle.write(proxy.python_logo().data)
</pre> </section> <section id="fault-objects"> <span id="id4"></span><h2>Fault Objects</h2> <dl class="py class"> <dt class="sig sig-object py" id="xmlrpc.client.Fault">
<code>class xmlrpc.client.Fault</code> </dt> <dd>
<p>A <a class="reference internal" href="#xmlrpc.client.Fault" title="xmlrpc.client.Fault"><code>Fault</code></a> object encapsulates the content of an XML-RPC fault tag. Fault objects have the following attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="xmlrpc.client.Fault.faultCode">
<code>faultCode</code> </dt> <dd>
<p>An int indicating the fault type.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="xmlrpc.client.Fault.faultString">
<code>faultString</code> </dt> <dd>
<p>A string containing a diagnostic message associated with the fault.</p> </dd>
</dl> </dd>
</dl> <p>In the following example we’re going to intentionally cause a <a class="reference internal" href="#xmlrpc.client.Fault" title="xmlrpc.client.Fault"><code>Fault</code></a> by returning a complex type object. The server code:</p> <pre data-language="python">from xmlrpc.server import SimpleXMLRPCServer
# A marshalling error is going to occur because we're returning a
# complex number
def add(x, y):
return x+y+0j
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(add, 'add')
server.serve_forever()
</pre> <p>The client code for the preceding server:</p> <pre data-language="python">import xmlrpc.client
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
try:
proxy.add(2, 5)
except xmlrpc.client.Fault as err:
print("A fault occurred")
print("Fault code: %d" % err.faultCode)
print("Fault string: %s" % err.faultString)
</pre> </section> <section id="protocolerror-objects"> <span id="protocol-error-objects"></span><h2>ProtocolError Objects</h2> <dl class="py class"> <dt class="sig sig-object py" id="xmlrpc.client.ProtocolError">
<code>class xmlrpc.client.ProtocolError</code> </dt> <dd>
<p>A <a class="reference internal" href="#xmlrpc.client.ProtocolError" title="xmlrpc.client.ProtocolError"><code>ProtocolError</code></a> object describes a protocol error in the underlying transport layer (such as a 404 ‘not found’ error if the server named by the URI does not exist). It has the following attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="xmlrpc.client.ProtocolError.url">
<code>url</code> </dt> <dd>
<p>The URI or URL that triggered the error.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="xmlrpc.client.ProtocolError.errcode">
<code>errcode</code> </dt> <dd>
<p>The error code.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="xmlrpc.client.ProtocolError.errmsg">
<code>errmsg</code> </dt> <dd>
<p>The error message or diagnostic string.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="xmlrpc.client.ProtocolError.headers">
<code>headers</code> </dt> <dd>
<p>A dict containing the headers of the HTTP/HTTPS request that triggered the error.</p> </dd>
</dl> </dd>
</dl> <p>In the following example we’re going to intentionally cause a <a class="reference internal" href="#xmlrpc.client.ProtocolError" title="xmlrpc.client.ProtocolError"><code>ProtocolError</code></a> by providing an invalid URI:</p> <pre data-language="python">import xmlrpc.client
# create a ServerProxy with a URI that doesn't respond to XMLRPC requests
proxy = xmlrpc.client.ServerProxy("http://google.com/")
try:
proxy.some_method()
except xmlrpc.client.ProtocolError as err:
print("A protocol error occurred")
print("URL: %s" % err.url)
print("HTTP/HTTPS headers: %s" % err.headers)
print("Error code: %d" % err.errcode)
print("Error message: %s" % err.errmsg)
</pre> </section> <section id="multicall-objects"> <h2>MultiCall Objects</h2> <p>The <a class="reference internal" href="#xmlrpc.client.MultiCall" title="xmlrpc.client.MultiCall"><code>MultiCall</code></a> object provides a way to encapsulate multiple calls to a remote server into a single request <a class="footnote-reference brackets" href="#id6" id="id5">1</a>.</p> <dl class="py class"> <dt class="sig sig-object py" id="xmlrpc.client.MultiCall">
<code>class xmlrpc.client.MultiCall(server)</code> </dt> <dd>
<p>Create an object used to boxcar method calls. <em>server</em> is the eventual target of the call. Calls can be made to the result object, but they will immediately return <code>None</code>, and only store the call name and parameters in the <a class="reference internal" href="#xmlrpc.client.MultiCall" title="xmlrpc.client.MultiCall"><code>MultiCall</code></a> object. Calling the object itself causes all stored calls to be transmitted as a single <code>system.multicall</code> request. The result of this call is a <a class="reference internal" href="../glossary#term-generator"><span class="xref std std-term">generator</span></a>; iterating over this generator yields the individual results.</p> </dd>
</dl> <p>A usage example of this class follows. The server code:</p> <pre data-language="python">from xmlrpc.server import SimpleXMLRPCServer
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x // y
# A simple server with simple arithmetic functions
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_multicall_functions()
server.register_function(add, 'add')
server.register_function(subtract, 'subtract')
server.register_function(multiply, 'multiply')
server.register_function(divide, 'divide')
server.serve_forever()
</pre> <p>The client code for the preceding server:</p> <pre data-language="python">import xmlrpc.client
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
multicall = xmlrpc.client.MultiCall(proxy)
multicall.add(7, 3)
multicall.subtract(7, 3)
multicall.multiply(7, 3)
multicall.divide(7, 3)
result = multicall()
print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))
</pre> </section> <section id="convenience-functions"> <h2>Convenience Functions</h2> <dl class="py function"> <dt class="sig sig-object py" id="xmlrpc.client.dumps">
<code>xmlrpc.client.dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)</code> </dt> <dd>
<p>Convert <em>params</em> into an XML-RPC request. or into a response if <em>methodresponse</em> is true. <em>params</em> can be either a tuple of arguments or an instance of the <a class="reference internal" href="#xmlrpc.client.Fault" title="xmlrpc.client.Fault"><code>Fault</code></a> exception class. If <em>methodresponse</em> is true, only a single value can be returned, meaning that <em>params</em> must be of length 1. <em>encoding</em>, if supplied, is the encoding to use in the generated XML; the default is UTF-8. Python’s <a class="reference internal" href="constants#None" title="None"><code>None</code></a> value cannot be used in standard XML-RPC; to allow using it via an extension, provide a true value for <em>allow_none</em>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="xmlrpc.client.loads">
<code>xmlrpc.client.loads(data, use_datetime=False, use_builtin_types=False)</code> </dt> <dd>
<p>Convert an XML-RPC request or response into Python objects, a <code>(params,
methodname)</code>. <em>params</em> is a tuple of argument; <em>methodname</em> is a string, or <code>None</code> if no method name is present in the packet. If the XML-RPC packet represents a fault condition, this function will raise a <a class="reference internal" href="#xmlrpc.client.Fault" title="xmlrpc.client.Fault"><code>Fault</code></a> exception. The <em>use_builtin_types</em> flag can be used to cause date/time values to be presented as <a class="reference internal" href="datetime#datetime.datetime" title="datetime.datetime"><code>datetime.datetime</code></a> objects and binary data to be presented as <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> objects; this flag is false by default.</p> <p>The obsolete <em>use_datetime</em> flag is similar to <em>use_builtin_types</em> but it applies only to date/time values.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>The <em>use_builtin_types</em> flag was added.</p> </div> </dd>
</dl> </section> <section id="example-of-client-usage"> <span id="xmlrpc-client-example"></span><h2>Example of Client Usage</h2> <pre data-language="python"># simple test program (from the XML-RPC specification)
from xmlrpc.client import ServerProxy, Error
# server = ServerProxy("http://localhost:8000") # local server
with ServerProxy("http://betty.userland.com") as proxy:
print(proxy)
try:
print(proxy.examples.getStateName(41))
except Error as v:
print("ERROR", v)
</pre> <p>To access an XML-RPC server through a HTTP proxy, you need to define a custom transport. The following example shows how:</p> <pre data-language="python">import http.client
import xmlrpc.client
class ProxiedTransport(xmlrpc.client.Transport):
def set_proxy(self, host, port=None, headers=None):
self.proxy = host, port
self.proxy_headers = headers
def make_connection(self, host):
connection = http.client.HTTPConnection(*self.proxy)
connection.set_tunnel(host, headers=self.proxy_headers)
self._connection = host, connection
return connection
transport = ProxiedTransport()
transport.set_proxy('proxy-server', 8080)
server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport)
print(server.examples.getStateName(41))
</pre> </section> <section id="example-of-client-and-server-usage"> <h2>Example of Client and Server Usage</h2> <p>See <a class="reference internal" href="xmlrpc.server#simplexmlrpcserver-example"><span class="std std-ref">SimpleXMLRPCServer Example</span></a>.</p> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="id6">
<code>1</code> </dt> <dd>
<p>This approach has been first presented in <a class="reference external" href="https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic">a discussion on xmlrpc.com</a>.</p> </dd> </dl> </section> <div class="_attribution">
<p class="_attribution-p">
© 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br>
<a href="https://docs.python.org/3.12/library/xmlrpc.client.html" class="_attribution-link">https://docs.python.org/3.12/library/xmlrpc.client.html</a>
</p>
</div>
|