xmlrpc.server — Basic XML-RPC servers

Source code:Lib/xmlrpc/server.py


Thexmlrpc.server module provides a basic server framework for XML-RPCservers written in Python. Servers can either be free standing, usingSimpleXMLRPCServer, or embedded in a CGI environment, usingCGIXMLRPCRequestHandler.

Warning

Thexmlrpc.server module is not secure against maliciouslyconstructed data. If you need to parse untrusted or unauthenticated data seeXML vulnerabilities.

Availability: not WASI.

This module does not work or is not available on WebAssembly. SeeWebAssembly platforms for more information.

classxmlrpc.server.SimpleXMLRPCServer(addr,requestHandler=SimpleXMLRPCRequestHandler,logRequests=True,allow_none=False,encoding=None,bind_and_activate=True,use_builtin_types=False)

Create a new server instance. This class provides methods for registration offunctions that can be called by the XML-RPC protocol. TherequestHandlerparameter should be a factory for request handler instances; it defaults toSimpleXMLRPCRequestHandler. Theaddr andrequestHandler parametersare passed to thesocketserver.TCPServer constructor. IflogRequestsis true (the default), requests will be logged; setting this parameter to falsewill turn off logging. Theallow_none andencoding parameters are passedon toxmlrpc.client and control the XML-RPC responses that will be returnedfrom the server. Thebind_and_activate parameter controls whetherserver_bind() andserver_activate() are called immediately by theconstructor; it defaults to true. Setting it to false allows code to manipulatetheallow_reuse_address class variable before the address is bound.Theuse_builtin_types parameter is passed to theloads() function and controls which types are processedwhen date/times values or binary data are received; it defaults to false.

Changed in version 3.3:Theuse_builtin_types flag was added.

classxmlrpc.server.CGIXMLRPCRequestHandler(allow_none=False,encoding=None,use_builtin_types=False)

Create a new instance to handle XML-RPC requests in a CGI environment. Theallow_none andencoding parameters are passed on toxmlrpc.clientand control the XML-RPC responses that will be returned from the server.Theuse_builtin_types parameter is passed to theloads() function and controls which types are processedwhen date/times values or binary data are received; it defaults to false.

Changed in version 3.3:Theuse_builtin_types flag was added.

classxmlrpc.server.SimpleXMLRPCRequestHandler

Create a new request handler instance. This request handler supportsPOSTrequests and modifies logging so that thelogRequests parameter to theSimpleXMLRPCServer constructor parameter is honored.

SimpleXMLRPCServer Objects

TheSimpleXMLRPCServer class is based onsocketserver.TCPServer and provides a means of creating simple, standalone XML-RPC servers.

SimpleXMLRPCServer.register_function(function=None,name=None)

Register a function that can respond to XML-RPC requests. Ifname is given,it will be the method name associated withfunction, otherwisefunction.__name__ will be used.name is a string, and may containcharacters not legal in Python identifiers, including the period character.

This method can also be used as a decorator. When used as a decorator,name can only be given as a keyword argument to registerfunction undername. If noname is given,function.__name__ will be used.

Changed in version 3.7:register_function() can be used as a decorator.

SimpleXMLRPCServer.register_instance(instance,allow_dotted_names=False)

Register an object which is used to expose method names which have not beenregistered usingregister_function(). Ifinstance contains a_dispatch() method, it is called with the requested method name and theparameters from the request. Its API isdef_dispatch(self,method,params)(note thatparams does not represent a variable argument list). If it callsan underlying function to perform its task, that function is called asfunc(*params), expanding the parameter list. The return value from_dispatch() is returned to the client as the result. Ifinstance doesnot have a_dispatch() method, it is searched for an attribute matchingthe name of the requested method.

If the optionalallow_dotted_names argument is true and the instance does nothave a_dispatch() method, then if the requested method name containsperiods, each component of the method name is searched for individually, withthe effect that a simple hierarchical search is performed. The value found fromthis search is then called with the parameters from the request, and the returnvalue is passed back to the client.

Warning

Enabling theallow_dotted_names option allows intruders to access yourmodule’s global variables and may allow intruders to execute arbitrary code onyour machine. Only use this option on a secure, closed network.

SimpleXMLRPCServer.register_introspection_functions()

Registers the XML-RPC introspection functionssystem.listMethods,system.methodHelp andsystem.methodSignature.

SimpleXMLRPCServer.register_multicall_functions()

Registers the XML-RPC multicall function system.multicall.

SimpleXMLRPCRequestHandler.rpc_paths

An attribute value that must be a tuple listing valid path portions of the URLfor receiving XML-RPC requests. Requests posted to other paths will result in a404 “no such page” HTTP error. If this tuple is empty, all paths will beconsidered valid. The default value is('/','/RPC2').

SimpleXMLRPCServer Example

Server code:

fromxmlrpc.serverimportSimpleXMLRPCServerfromxmlrpc.serverimportSimpleXMLRPCRequestHandler# Restrict to a particular path.classRequestHandler(SimpleXMLRPCRequestHandler):rpc_paths=('/RPC2',)# Create serverwithSimpleXMLRPCServer(('localhost',8000),requestHandler=RequestHandler)asserver:server.register_introspection_functions()# Register pow() function; this will use the value of# pow.__name__ as the name, which is just 'pow'.server.register_function(pow)# Register a function under a different namedefadder_function(x,y):returnx+yserver.register_function(adder_function,'add')# Register an instance; all the methods of the instance are# published as XML-RPC methods (in this case, just 'mul').classMyFuncs:defmul(self,x,y):returnx*yserver.register_instance(MyFuncs())# Run the server's main loopserver.serve_forever()

The following client code will call the methods made available by the precedingserver:

importxmlrpc.clients=xmlrpc.client.ServerProxy('http://localhost:8000')print(s.pow(2,3))# Returns 2**3 = 8print(s.add(2,3))# Returns 5print(s.mul(5,2))# Returns 5*2 = 10# Print list of available methodsprint(s.system.listMethods())

register_function() can also be used as a decorator. The previous serverexample can register functions in a decorator way:

fromxmlrpc.serverimportSimpleXMLRPCServerfromxmlrpc.serverimportSimpleXMLRPCRequestHandlerclassRequestHandler(SimpleXMLRPCRequestHandler):rpc_paths=('/RPC2',)withSimpleXMLRPCServer(('localhost',8000),requestHandler=RequestHandler)asserver:server.register_introspection_functions()# Register pow() function; this will use the value of# pow.__name__ as the name, which is just 'pow'.server.register_function(pow)# Register a function under a different name, using# register_function as a decorator. *name* can only be given# as a keyword argument.@server.register_function(name='add')defadder_function(x,y):returnx+y# Register a function under function.__name__.@server.register_functiondefmul(x,y):returnx*yserver.serve_forever()

The following example included in theLib/xmlrpc/server.py module showsa server allowing dotted names and registering a multicall function.

Warning

Enabling theallow_dotted_names option allows intruders to access yourmodule’s global variables and may allow intruders to execute arbitrary code onyour machine. Only use this example only within a secure, closed network.

importdatetimeclassExampleService:defgetData(self):return'42'classcurrentTime:@staticmethoddefgetCurrentTime():returndatetime.datetime.now()withSimpleXMLRPCServer(("localhost",8000))asserver:server.register_function(pow)server.register_function(lambdax,y:x+y,'add')server.register_instance(ExampleService(),allow_dotted_names=True)server.register_multicall_functions()print('Serving XML-RPC on localhost port 8000')try:server.serve_forever()exceptKeyboardInterrupt:print("\nKeyboard interrupt received, exiting.")sys.exit(0)

This ExampleService demo can be invoked from the command line:

python-mxmlrpc.server

The client that interacts with the above server is included inLib/xmlrpc/client.py:

server=ServerProxy("http://localhost:8000")try:print(server.currentTime.getCurrentTime())exceptErrorasv:print("ERROR",v)multi=MultiCall(server)multi.getData()multi.pow(2,9)multi.add(1,2)try:forresponseinmulti():print(response)exceptErrorasv:print("ERROR",v)

This client which interacts with the demo XMLRPC server can be invoked as:

python-mxmlrpc.client

CGIXMLRPCRequestHandler

TheCGIXMLRPCRequestHandler class can be used to handle XML-RPCrequests sent to Python CGI scripts.

CGIXMLRPCRequestHandler.register_function(function=None,name=None)

Register a function that can respond to XML-RPC requests. Ifname is given,it will be the method name associated withfunction, otherwisefunction.__name__ will be used.name is a string, and may containcharacters not legal in Python identifiers, including the period character.

This method can also be used as a decorator. When used as a decorator,name can only be given as a keyword argument to registerfunction undername. If noname is given,function.__name__ will be used.

Changed in version 3.7:register_function() can be used as a decorator.

CGIXMLRPCRequestHandler.register_instance(instance)

Register an object which is used to expose method names which have not beenregistered usingregister_function(). If instance contains a_dispatch() method, it is called with the requested method name and theparameters from the request; the return value is returned to the client as theresult. If instance does not have a_dispatch() method, it is searchedfor an attribute matching the name of the requested method; if the requestedmethod name contains periods, each component of the method name is searched forindividually, with the effect that a simple hierarchical search is performed.The value found from this search is then called with the parameters from therequest, and the return value is passed back to the client.

CGIXMLRPCRequestHandler.register_introspection_functions()

Register the XML-RPC introspection functionssystem.listMethods,system.methodHelp andsystem.methodSignature.

CGIXMLRPCRequestHandler.register_multicall_functions()

Register the XML-RPC multicall functionsystem.multicall.

CGIXMLRPCRequestHandler.handle_request(request_text=None)

Handle an XML-RPC request. Ifrequest_text is given, it should be the POSTdata provided by the HTTP server, otherwise the contents of stdin will be used.

Example:

classMyFuncs:defmul(self,x,y):returnx*yhandler=CGIXMLRPCRequestHandler()handler.register_function(pow)handler.register_function(lambdax,y:x+y,'add')handler.register_introspection_functions()handler.register_instance(MyFuncs())handler.handle_request()

Documenting XMLRPC server

These classes extend the above classes to serve HTML documentation in responseto HTTP GET requests. Servers can either be free standing, usingDocXMLRPCServer, or embedded in a CGI environment, usingDocCGIXMLRPCRequestHandler.

classxmlrpc.server.DocXMLRPCServer(addr,requestHandler=DocXMLRPCRequestHandler,logRequests=True,allow_none=False,encoding=None,bind_and_activate=True,use_builtin_types=True)

Create a new server instance. All parameters have the same meaning as forSimpleXMLRPCServer;requestHandler defaults toDocXMLRPCRequestHandler.

Changed in version 3.3:Theuse_builtin_types flag was added.

classxmlrpc.server.DocCGIXMLRPCRequestHandler

Create a new instance to handle XML-RPC requests in a CGI environment.

classxmlrpc.server.DocXMLRPCRequestHandler

Create a new request handler instance. This request handler supports XML-RPCPOST requests, documentation GET requests, and modifies logging so that thelogRequests parameter to theDocXMLRPCServer constructor parameter ishonored.

DocXMLRPCServer Objects

TheDocXMLRPCServer class is derived fromSimpleXMLRPCServerand provides a means of creating self-documenting, stand alone XML-RPCservers. HTTP POST requests are handled as XML-RPC method calls. HTTP GETrequests are handled by generating pydoc-style HTML documentation. This allows aserver to provide its own web-based documentation.

DocXMLRPCServer.set_server_title(server_title)

Set the title used in the generated HTML documentation. This title will be usedinside the HTML “title” element.

DocXMLRPCServer.set_server_name(server_name)

Set the name used in the generated HTML documentation. This name will appear atthe top of the generated documentation inside a “h1” element.

DocXMLRPCServer.set_server_documentation(server_documentation)

Set the description used in the generated HTML documentation. This descriptionwill appear as a paragraph, below the server name, in the documentation.

DocCGIXMLRPCRequestHandler

TheDocCGIXMLRPCRequestHandler class is derived fromCGIXMLRPCRequestHandler and provides a means of creatingself-documenting, XML-RPC CGI scripts. HTTP POST requests are handled as XML-RPCmethod calls. HTTP GET requests are handled by generating pydoc-style HTMLdocumentation. This allows a server to provide its own web-based documentation.

DocCGIXMLRPCRequestHandler.set_server_title(server_title)

Set the title used in the generated HTML documentation. This title will be usedinside the HTML “title” element.

DocCGIXMLRPCRequestHandler.set_server_name(server_name)

Set the name used in the generated HTML documentation. This name will appear atthe top of the generated documentation inside a “h1” element.

DocCGIXMLRPCRequestHandler.set_server_documentation(server_documentation)

Set the description used in the generated HTML documentation. This descriptionwill appear as a paragraph, below the server name, in the documentation.