1:mod:`xmlrpc.server` --- Basic XML-RPC servers 2============================================== 3 4.. module:: xmlrpc.server 5 :synopsis: Basic XML-RPC server implementations. 6 7.. moduleauthor:: Brian Quinlan <[email protected]> 8.. sectionauthor:: Fred L. Drake, Jr. <[email protected]> 9 10**Source code:** :source:`Lib/xmlrpc/server.py` 11 12-------------- 13 14The :mod:`xmlrpc.server` module provides a basic server framework for XML-RPC 15servers written in Python. Servers can either be free standing, using 16:class:`SimpleXMLRPCServer`, or embedded in a CGI environment, using 17:class:`CGIXMLRPCRequestHandler`. 18 19 20.. warning:: 21 22 The :mod:`xmlrpc.server` module is not secure against maliciously 23 constructed data. If you need to parse untrusted or unauthenticated data see 24 :ref:`xml-vulnerabilities`. 25 26.. include:: ../includes/wasm-notavail.rst 27 28.. class:: SimpleXMLRPCServer(addr, requestHandler=SimpleXMLRPCRequestHandler,\ 29 logRequests=True, allow_none=False, encoding=None,\ 30 bind_and_activate=True, use_builtin_types=False) 31 32 Create a new server instance. This class provides methods for registration of 33 functions that can be called by the XML-RPC protocol. The *requestHandler* 34 parameter should be a factory for request handler instances; it defaults to 35 :class:`SimpleXMLRPCRequestHandler`. The *addr* and *requestHandler* parameters 36 are passed to the :class:`socketserver.TCPServer` constructor. If *logRequests* 37 is true (the default), requests will be logged; setting this parameter to false 38 will turn off logging. The *allow_none* and *encoding* parameters are passed 39 on to :mod:`xmlrpc.client` and control the XML-RPC responses that will be returned 40 from the server. The *bind_and_activate* parameter controls whether 41 :meth:`server_bind` and :meth:`server_activate` are called immediately by the 42 constructor; it defaults to true. Setting it to false allows code to manipulate 43 the *allow_reuse_address* class variable before the address is bound. 44 The *use_builtin_types* parameter is passed to the 45 :func:`~xmlrpc.client.loads` function and controls which types are processed 46 when date/times values or binary data are received; it defaults to false. 47 48 .. versionchanged:: 3.3 49 The *use_builtin_types* flag was added. 50 51 52.. class:: CGIXMLRPCRequestHandler(allow_none=False, encoding=None,\ 53 use_builtin_types=False) 54 55 Create a new instance to handle XML-RPC requests in a CGI environment. The 56 *allow_none* and *encoding* parameters are passed on to :mod:`xmlrpc.client` 57 and control the XML-RPC responses that will be returned from the server. 58 The *use_builtin_types* parameter is passed to the 59 :func:`~xmlrpc.client.loads` function and controls which types are processed 60 when date/times values or binary data are received; it defaults to false. 61 62 .. versionchanged:: 3.3 63 The *use_builtin_types* flag was added. 64 65 66.. class:: SimpleXMLRPCRequestHandler() 67 68 Create a new request handler instance. This request handler supports ``POST`` 69 requests and modifies logging so that the *logRequests* parameter to the 70 :class:`SimpleXMLRPCServer` constructor parameter is honored. 71 72 73.. _simple-xmlrpc-servers: 74 75SimpleXMLRPCServer Objects 76-------------------------- 77 78The :class:`SimpleXMLRPCServer` class is based on 79:class:`socketserver.TCPServer` and provides a means of creating simple, stand 80alone XML-RPC servers. 81 82 83.. method:: SimpleXMLRPCServer.register_function(function=None, name=None) 84 85 Register a function that can respond to XML-RPC requests. If *name* is given, 86 it will be the method name associated with *function*, otherwise 87 ``function.__name__`` will be used. *name* is a string, and may contain 88 characters not legal in Python identifiers, including the period character. 89 90 This method can also be used as a decorator. When used as a decorator, 91 *name* can only be given as a keyword argument to register *function* under 92 *name*. If no *name* is given, ``function.__name__`` will be used. 93 94 .. versionchanged:: 3.7 95 :meth:`register_function` can be used as a decorator. 96 97 98.. method:: SimpleXMLRPCServer.register_instance(instance, allow_dotted_names=False) 99 100 Register an object which is used to expose method names which have not been 101 registered using :meth:`register_function`. If *instance* contains a 102 :meth:`_dispatch` method, it is called with the requested method name and the 103 parameters from the request. Its API is ``def _dispatch(self, method, params)`` 104 (note that *params* does not represent a variable argument list). If it calls 105 an underlying function to perform its task, that function is called as 106 ``func(*params)``, expanding the parameter list. The return value from 107 :meth:`_dispatch` is returned to the client as the result. If *instance* does 108 not have a :meth:`_dispatch` method, it is searched for an attribute matching 109 the name of the requested method. 110 111 If the optional *allow_dotted_names* argument is true and the instance does not 112 have a :meth:`_dispatch` method, then if the requested method name contains 113 periods, each component of the method name is searched for individually, with 114 the effect that a simple hierarchical search is performed. The value found from 115 this search is then called with the parameters from the request, and the return 116 value is passed back to the client. 117 118 .. warning:: 119 120 Enabling the *allow_dotted_names* option allows intruders to access your 121 module's global variables and may allow intruders to execute arbitrary code on 122 your machine. Only use this option on a secure, closed network. 123 124 125.. method:: SimpleXMLRPCServer.register_introspection_functions() 126 127 Registers the XML-RPC introspection functions ``system.listMethods``, 128 ``system.methodHelp`` and ``system.methodSignature``. 129 130 131.. method:: SimpleXMLRPCServer.register_multicall_functions() 132 133 Registers the XML-RPC multicall function system.multicall. 134 135 136.. attribute:: SimpleXMLRPCRequestHandler.rpc_paths 137 138 An attribute value that must be a tuple listing valid path portions of the URL 139 for receiving XML-RPC requests. Requests posted to other paths will result in a 140 404 "no such page" HTTP error. If this tuple is empty, all paths will be 141 considered valid. The default value is ``('/', '/RPC2')``. 142 143 144.. _simplexmlrpcserver-example: 145 146SimpleXMLRPCServer Example 147^^^^^^^^^^^^^^^^^^^^^^^^^^ 148Server code:: 149 150 from xmlrpc.server import SimpleXMLRPCServer 151 from xmlrpc.server import SimpleXMLRPCRequestHandler 152 153 # Restrict to a particular path. 154 class RequestHandler(SimpleXMLRPCRequestHandler): 155 rpc_paths = ('/RPC2',) 156 157 # Create server 158 with SimpleXMLRPCServer(('localhost', 8000), 159 requestHandler=RequestHandler) as server: 160 server.register_introspection_functions() 161 162 # Register pow() function; this will use the value of 163 # pow.__name__ as the name, which is just 'pow'. 164 server.register_function(pow) 165 166 # Register a function under a different name 167 def adder_function(x, y): 168 return x + y 169 server.register_function(adder_function, 'add') 170 171 # Register an instance; all the methods of the instance are 172 # published as XML-RPC methods (in this case, just 'mul'). 173 class MyFuncs: 174 def mul(self, x, y): 175 return x * y 176 177 server.register_instance(MyFuncs()) 178 179 # Run the server's main loop 180 server.serve_forever() 181 182The following client code will call the methods made available by the preceding 183server:: 184 185 import xmlrpc.client 186 187 s = xmlrpc.client.ServerProxy('http://localhost:8000') 188 print(s.pow(2,3)) # Returns 2**3 = 8 189 print(s.add(2,3)) # Returns 5 190 print(s.mul(5,2)) # Returns 5*2 = 10 191 192 # Print list of available methods 193 print(s.system.listMethods()) 194 195:meth:`register_function` can also be used as a decorator. The previous server 196example can register functions in a decorator way:: 197 198 from xmlrpc.server import SimpleXMLRPCServer 199 from xmlrpc.server import SimpleXMLRPCRequestHandler 200 201 class RequestHandler(SimpleXMLRPCRequestHandler): 202 rpc_paths = ('/RPC2',) 203 204 with SimpleXMLRPCServer(('localhost', 8000), 205 requestHandler=RequestHandler) as server: 206 server.register_introspection_functions() 207 208 # Register pow() function; this will use the value of 209 # pow.__name__ as the name, which is just 'pow'. 210 server.register_function(pow) 211 212 # Register a function under a different name, using 213 # register_function as a decorator. *name* can only be given 214 # as a keyword argument. 215 @server.register_function(name='add') 216 def adder_function(x, y): 217 return x + y 218 219 # Register a function under function.__name__. 220 @server.register_function 221 def mul(x, y): 222 return x * y 223 224 server.serve_forever() 225 226The following example included in the :file:`Lib/xmlrpc/server.py` module shows 227a server allowing dotted names and registering a multicall function. 228 229.. warning:: 230 231 Enabling the *allow_dotted_names* option allows intruders to access your 232 module's global variables and may allow intruders to execute arbitrary code on 233 your machine. Only use this example only within a secure, closed network. 234 235:: 236 237 import datetime 238 239 class ExampleService: 240 def getData(self): 241 return '42' 242 243 class currentTime: 244 @staticmethod 245 def getCurrentTime(): 246 return datetime.datetime.now() 247 248 with SimpleXMLRPCServer(("localhost", 8000)) as server: 249 server.register_function(pow) 250 server.register_function(lambda x,y: x+y, 'add') 251 server.register_instance(ExampleService(), allow_dotted_names=True) 252 server.register_multicall_functions() 253 print('Serving XML-RPC on localhost port 8000') 254 try: 255 server.serve_forever() 256 except KeyboardInterrupt: 257 print("\nKeyboard interrupt received, exiting.") 258 sys.exit(0) 259 260This ExampleService demo can be invoked from the command line:: 261 262 python -m xmlrpc.server 263 264 265The client that interacts with the above server is included in 266``Lib/xmlrpc/client.py``:: 267 268 server = ServerProxy("http://localhost:8000") 269 270 try: 271 print(server.currentTime.getCurrentTime()) 272 except Error as v: 273 print("ERROR", v) 274 275 multi = MultiCall(server) 276 multi.getData() 277 multi.pow(2,9) 278 multi.add(1,2) 279 try: 280 for response in multi(): 281 print(response) 282 except Error as v: 283 print("ERROR", v) 284 285This client which interacts with the demo XMLRPC server can be invoked as:: 286 287 python -m xmlrpc.client 288 289 290CGIXMLRPCRequestHandler 291----------------------- 292 293The :class:`CGIXMLRPCRequestHandler` class can be used to handle XML-RPC 294requests sent to Python CGI scripts. 295 296 297.. method:: CGIXMLRPCRequestHandler.register_function(function=None, name=None) 298 299 Register a function that can respond to XML-RPC requests. If *name* is given, 300 it will be the method name associated with *function*, otherwise 301 ``function.__name__`` will be used. *name* is a string, and may contain 302 characters not legal in Python identifiers, including the period character. 303 304 This method can also be used as a decorator. When used as a decorator, 305 *name* can only be given as a keyword argument to register *function* under 306 *name*. If no *name* is given, ``function.__name__`` will be used. 307 308 .. versionchanged:: 3.7 309 :meth:`register_function` can be used as a decorator. 310 311 312.. method:: CGIXMLRPCRequestHandler.register_instance(instance) 313 314 Register an object which is used to expose method names which have not been 315 registered using :meth:`register_function`. If instance contains a 316 :meth:`_dispatch` method, it is called with the requested method name and the 317 parameters from the request; the return value is returned to the client as the 318 result. If instance does not have a :meth:`_dispatch` method, it is searched 319 for an attribute matching the name of the requested method; if the requested 320 method name contains periods, each component of the method name is searched for 321 individually, with the effect that a simple hierarchical search is performed. 322 The value found from this search is then called with the parameters from the 323 request, and the return value is passed back to the client. 324 325 326.. method:: CGIXMLRPCRequestHandler.register_introspection_functions() 327 328 Register the XML-RPC introspection functions ``system.listMethods``, 329 ``system.methodHelp`` and ``system.methodSignature``. 330 331 332.. method:: CGIXMLRPCRequestHandler.register_multicall_functions() 333 334 Register the XML-RPC multicall function ``system.multicall``. 335 336 337.. method:: CGIXMLRPCRequestHandler.handle_request(request_text=None) 338 339 Handle an XML-RPC request. If *request_text* is given, it should be the POST 340 data provided by the HTTP server, otherwise the contents of stdin will be used. 341 342Example:: 343 344 class MyFuncs: 345 def mul(self, x, y): 346 return x * y 347 348 349 handler = CGIXMLRPCRequestHandler() 350 handler.register_function(pow) 351 handler.register_function(lambda x,y: x+y, 'add') 352 handler.register_introspection_functions() 353 handler.register_instance(MyFuncs()) 354 handler.handle_request() 355 356 357Documenting XMLRPC server 358------------------------- 359 360These classes extend the above classes to serve HTML documentation in response 361to HTTP GET requests. Servers can either be free standing, using 362:class:`DocXMLRPCServer`, or embedded in a CGI environment, using 363:class:`DocCGIXMLRPCRequestHandler`. 364 365 366.. class:: DocXMLRPCServer(addr, requestHandler=DocXMLRPCRequestHandler,\ 367 logRequests=True, allow_none=False, encoding=None,\ 368 bind_and_activate=True, use_builtin_types=True) 369 370 Create a new server instance. All parameters have the same meaning as for 371 :class:`SimpleXMLRPCServer`; *requestHandler* defaults to 372 :class:`DocXMLRPCRequestHandler`. 373 374 .. versionchanged:: 3.3 375 The *use_builtin_types* flag was added. 376 377 378.. class:: DocCGIXMLRPCRequestHandler() 379 380 Create a new instance to handle XML-RPC requests in a CGI environment. 381 382 383.. class:: DocXMLRPCRequestHandler() 384 385 Create a new request handler instance. This request handler supports XML-RPC 386 POST requests, documentation GET requests, and modifies logging so that the 387 *logRequests* parameter to the :class:`DocXMLRPCServer` constructor parameter is 388 honored. 389 390 391.. _doc-xmlrpc-servers: 392 393DocXMLRPCServer Objects 394----------------------- 395 396The :class:`DocXMLRPCServer` class is derived from :class:`SimpleXMLRPCServer` 397and provides a means of creating self-documenting, stand alone XML-RPC 398servers. HTTP POST requests are handled as XML-RPC method calls. HTTP GET 399requests are handled by generating pydoc-style HTML documentation. This allows a 400server to provide its own web-based documentation. 401 402 403.. method:: DocXMLRPCServer.set_server_title(server_title) 404 405 Set the title used in the generated HTML documentation. This title will be used 406 inside the HTML "title" element. 407 408 409.. method:: DocXMLRPCServer.set_server_name(server_name) 410 411 Set the name used in the generated HTML documentation. This name will appear at 412 the top of the generated documentation inside a "h1" element. 413 414 415.. method:: DocXMLRPCServer.set_server_documentation(server_documentation) 416 417 Set the description used in the generated HTML documentation. This description 418 will appear as a paragraph, below the server name, in the documentation. 419 420 421DocCGIXMLRPCRequestHandler 422-------------------------- 423 424The :class:`DocCGIXMLRPCRequestHandler` class is derived from 425:class:`CGIXMLRPCRequestHandler` and provides a means of creating 426self-documenting, XML-RPC CGI scripts. HTTP POST requests are handled as XML-RPC 427method calls. HTTP GET requests are handled by generating pydoc-style HTML 428documentation. This allows a server to provide its own web-based documentation. 429 430 431.. method:: DocCGIXMLRPCRequestHandler.set_server_title(server_title) 432 433 Set the title used in the generated HTML documentation. This title will be used 434 inside the HTML "title" element. 435 436 437.. method:: DocCGIXMLRPCRequestHandler.set_server_name(server_name) 438 439 Set the name used in the generated HTML documentation. This name will appear at 440 the top of the generated documentation inside a "h1" element. 441 442 443.. method:: DocCGIXMLRPCRequestHandler.set_server_documentation(server_documentation) 444 445 Set the description used in the generated HTML documentation. This description 446 will appear as a paragraph, below the server name, in the documentation. 447