[@sdZddlmZmZmZmZmZddlmZddlZ ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZyddlZWnek rdZYnXdddZdd ZGd d d ZGd d d eZGddde jeZGdddeZGdddeZGdddejZGdddZGdddeZGdddeeZGdddeeZ e!dkrddl"Z"Gdd d Z#ed!d"fZ$e$j%e&e$j%d#d$d%e$j'e#d&de$j(e)d'e)d(ye$j*Wn3e+k re)d)e$j,e j-dYnXndS)*a XML-RPC Servers. This module can be used to create simple XML-RPC servers by creating a server and either installing functions, a class instance, or by extending the SimpleXMLRPCServer class. It can also be used to handle XML-RPC requests in a CGI environment using CGIXMLRPCRequestHandler. The Doc* classes can be used to create XML-RPC servers that serve pydoc-style documentation in response to HTTP GET requests. This documentation is dynamically generated based on the functions and methods registered with the server. A list of possible usage patterns follows: 1. Install functions: server = SimpleXMLRPCServer(("localhost", 8000)) server.register_function(pow) server.register_function(lambda x,y: x+y, 'add') server.serve_forever() 2. Install an instance: class MyFuncs: def __init__(self): # make all of the sys functions available through sys.func_name import sys self.sys = sys def _listMethods(self): # implement this method so that system.listMethods # knows to advertise the sys methods return list_public_methods(self) + \ ['sys.' + method for method in list_public_methods(self.sys)] def pow(self, x, y): return pow(x, y) def add(self, x, y) : return x + y server = SimpleXMLRPCServer(("localhost", 8000)) server.register_introspection_functions() server.register_instance(MyFuncs()) server.serve_forever() 3. Install an instance with custom dispatch method: class Math: def _listMethods(self): # this method must be present for system.listMethods # to work return ['add', 'pow'] def _methodHelp(self, method): # this method must be present for system.methodHelp # to work if method == 'add': return "add(2,3) => 5" elif method == 'pow': return "pow(x, y[, z]) => number" else: # By convention, return empty # string if no help is available return "" def _dispatch(self, method, params): if method == 'pow': return pow(*params) elif method == 'add': return params[0] + params[1] else: raise ValueError('bad method') server = SimpleXMLRPCServer(("localhost", 8000)) server.register_introspection_functions() server.register_instance(Math()) server.serve_forever() 4. Subclass SimpleXMLRPCServer: class MathServer(SimpleXMLRPCServer): def _dispatch(self, method, params): try: # We are forcing the 'export_' prefix on methods that are # callable through XML-RPC to prevent potential security # problems func = getattr(self, 'export_' + method) except AttributeError: raise Exception('method "%s" is not supported' % method) else: return func(*params) def export_add(self, x, y): return x + y server = MathServer(("localhost", 8000)) server.serve_forever() 5. CGI script: server = CGIXMLRPCRequestHandler() server.register_function(pow) server.handle_request() )Faultdumpsloads gzip_encode gzip_decode)BaseHTTPRequestHandlerNTcCsg|r|jd}n |g}x?|D]7}|jdrPtd|q(t||}q(W|S)aGresolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. If the optional allow_dotted_names argument is false, dots are not supported and this function operates similar to getattr(obj, attr). ._z(attempt to access private attribute "%s")split startswithAttributeErrorgetattr)objattrallow_dotted_namesZattrsir#/usr/lib/python3.4/xmlrpc/server.pyresolve_dotted_attributezs   rcsfddtDS)zkReturns a list of attribute strings, found in the specified object, which represent callable attributescs;g|]1}|jd rtt|r|qS)r )r callabler ).0Zmember)rrr s z'list_public_methods..)dir)rr)rrlist_public_methodssrc@seZdZdZdddddZdddZddd Zd d Zd d ZddddZ ddZ ddZ ddZ ddZ ddZdS)SimpleXMLRPCDispatchera&Mix-in class that dispatches XML-RPC requests. This class is used to register XML-RPC method handlers and then to dispatch them. This class doesn't need to be instanced directly when used by SimpleXMLRPCServer but it can be instanced when used by the MultiPathXMLRPCServer FNcCs7i|_d|_||_|p$d|_||_dS)Nzutf-8)funcsinstance allow_noneencodinguse_builtin_types)selfrrrrrr__init__s    zSimpleXMLRPCDispatcher.__init__cCs||_||_dS)aRegisters an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches a XML-RPC request, then it will be called instead of the registered instance. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch method, method names containing dots are supported and resolved, as long as none of the name segments start with an '_'. *** SECURITY WARNING: *** Enabling the allow_dotted_names options allows intruders to access your module's global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network. N)rr)r rrrrrregister_instances! z(SimpleXMLRPCDispatcher.register_instancecCs)|dkr|j}n||j| ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.N _listMethodsr.)setrkeysrhasattrr=rsorted)r methodsrrrr'sz)SimpleXMLRPCDispatcher.system_listMethodscCsdS)a#system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.zsignatures not supportedr)r method_namerrrr($s z-SimpleXMLRPCDispatcher.system_methodSignaturec Csd}||jkr%|j|}nz|jdk rt|jdrV|jj|St|jdsyt|j||j}Wqtk rYqXqn|dkrdStj|SdS)zsystem.methodHelp('add') => "Adds two integers together" Returns a string containing documentation for the specified method.N _methodHelpr.) rrr@rDrrr pydocgetdoc)r rCr6rrrr)1s"   z(SimpleXMLRPCDispatcher.system_methodHelpc Csg}x|D]}|d}|d}y |j|j||gWq tk r}z&|ji|jd6|jd6WYdd}~Xq tj\}}} |jidd6d||fd6Yq Xq W|S)zsystem.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => [[4], ...] Allows the caller to package multiple XML-RPC calls into a single request. See http://www.xmlrpc.com/discuss/msgReader$1208 Z methodNamer5 faultCode faultStringNr-z%s:%s)appendr.rrHrIr/r0) r Z call_listresultscallrCr5r8r9r:r;rrrr+Ps        z'SimpleXMLRPCDispatcher.system_multicallcCsd}y|j|}Wnztk r|jdk rt|jdr[|jj||Syt|j||j}Wqtk rYqXnYnX|dk r||Std|dS)aDispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called. Nr.zmethod "%s" is not supported) rKeyErrorrr@r.rrr Exception)r r6r5funcrrrr.ps"     z SimpleXMLRPCDispatcher._dispatch)r# __module__ __qualname____doc__r!r"r%r*r,r<r'r(r)r+r.rrrrrs $ %   rc@seZdZdZdZdZdZdZej dej ej BZ dd Z d d Zd d ZddZddZddddZdS)SimpleXMLRPCRequestHandlerzSimple XML-RPC request handler class. Handles all HTTP POST requests and attempts to decode them as XML-RPC requests. //RPC2ixr-Tz \s* ([^\s;]+) \s* #content-coding (;\s* q \s*=\s* ([0-9\.]+))? #q cCsi}|jjdd}xl|jdD][}|jj|}|r+|jd}|rjt|nd}|||jd%sz'http://www.rfc-editor.org/rfc/rfc%d.txtz(http://www.python.org/dev/peps/pep-%04d/r-(zself.%sNrE) escaperrsearchspanrJgroupsreplacernZnamelinkrr)r textrrclassesrBrKherepatternr[startendallZschemeZrfcZpepZselfdotr$Zurlrrrmarkups8  " zServerHTMLDoc.markupc Cs|r|jpdd|}d} d|j||j|f} tj|rtj|} tj| jdd| j| j| j d| j d|j } n]tj |rtj|} tj| j| j| j| j d| j d|j } nd} t |tr5|d p| } |dp/d} ntj|} | | | oa|jd | }|j| |j|||}|od |}d ||fS) z;Produce HTML documentation for a function or method object.rErz$%sr-N annotations formatvaluez(...)rz'%sz
%s
z
%s
%s
)r#rinspectZismethodZgetfullargspecZ formatargspecargsZvarargsZvarkwZdefaultsrrZ isfunction isinstancetuplerFrGZgreyr preformat)r objectr$modrrrBZclZanchorZnotetitlerZargspecZ docstringZdecldocrrr docroutines<   zServerHTMLDoc.docroutinec Csi}x6|jD](\}}d|||<||||%sz#ffffffz#7799eez %sz

%s

rZMethodsz#eeaa77rE) itemsrZheadingrrrArJrZ bigsectionrr) r server_nameZpackage_documentationrBZfdictkeyvalueheadresultrcontentsZ method_itemsrrr docservers" # zServerHTMLDoc.docserver)r#rPrQrRrrrrrrrrs ),rc@sReZdZdZddZddZddZdd Zd d Zd S) XMLRPCDocGeneratorzGenerates documentation for an XML-RPC server. This class is designed as mix-in and should not be constructed directly. cCsd|_d|_d|_dS)NzXML-RPC Server DocumentationzGThis server exports the following methods through the XML-RPC protocol.)rserver_documentation server_title)r rrrr!2s  zXMLRPCDocGenerator.__init__cCs ||_dS)z8Set the HTML title of the generated server documentationN)r)r rrrrset_server_title:sz#XMLRPCDocGenerator.set_server_titlecCs ||_dS)z7Set the name of the generated HTML server documentationN)r)r rrrrset_server_name?sz"XMLRPCDocGenerator.set_server_namecCs ||_dS)z3Set the documentation string for the entire server.N)r)r rrrrset_server_documentationDsz+XMLRPCDocGenerator.set_server_documentationc Cspi}x0|jD]"}||jkr8|j|}n|jdk rddg}t|jdr~|jj||d html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can choose to implement the _get_method_argstring(method_name) method to provide the argument string used in the documentation and the _methodHelp(method_name) method to provide the help text used in the documentation.N_get_method_argstringrrDr-r.zACould not find method in self.functions and no instance installed)NN)r'rrr@rrDrrr AssertionErrorrrrrZpager)r rBrCr6Z method_infoZ documenterZ documentationrrrgenerate_html_documentationIs:          z.XMLRPCDocGenerator.generate_html_documentationN) r#rPrQrRr!rrrrrrrrr+s     rc@s"eZdZdZddZdS)DocXMLRPCRequestHandlerzXML-RPC and documentation request handler class. Handles all HTTP POST requests and attempts to decode them as XML-RPC requests. Handles all HTTP GET requests and interprets them as requests for documentation. cCs|js|jdS|jjjd}|jd|jdd|jdtt||j |j j |dS)z}Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. Nzutf-8rjz Content-typez text/htmlzContent-length) rcrmrtrr1rurvrwrqrzr}r~)r r7rrrdo_GETs    zDocXMLRPCRequestHandler.do_GETN)r#rPrQrRrrrrrr|s rc@s4eZdZdZedddddddZdS)DocXMLRPCServerzXML-RPC and HTML documentation server. Adds the ability to serve server documentation to the capabilities of SimpleXMLRPCServer. TFNc Cs3tj||||||||tj|dS)N)rr!r)r rrrrrrrrrrr!s zDocXMLRPCServer.__init__)r#rPrQrRrr!rrrrrs  rc@s.eZdZdZddZddZdS)DocCGIXMLRPCRequestHandlerzJHandler for XML-RPC data and documentation requests passed through CGIcCsn|jjd}tdtdt|ttjjtjjj|tjjjdS)z}Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. zutf-8zContent-Type: text/htmlzContent-Length: %dN) rr1rrqr/rrrr~)r r7rrrrs  z%DocCGIXMLRPCRequestHandler.handle_getcCstj|tj|dS)N)rr!r)r rrrr!s z#DocCGIXMLRPCRequestHandler.__init__N)r#rPrQrRrr!rrrrrs  r__main__c@s/eZdZddZGdddZdS)ExampleServicecCsdS)NZ42r)r rrrgetDataszExampleService.getDatac@s"eZdZeddZdS)zExampleService.currentTimecCs tjjS)N)datetimeZnowrrrrgetCurrentTimesz)ExampleService.currentTime.getCurrentTimeN)r#rPrQ staticmethodrrrrr currentTimes rN)r#rPrQrrrrrrrs  rZ localhosti@cCs||S)Nr)xyrrrsraddrz&Serving XML-RPC on localhost port 8000zKIt is advisable to run this example server within a secure, closed network.z& Keyboard interrupt received, exiting.).rRZ xmlrpc.clientrrrrrZ http.serverrrrr/rrrFrrxZfcntl ImportErrorrrrrSrrrrZHTMLDocrrrrrr#rrrtr%powr"r,rZ serve_foreverKeyboardInterruptZ server_closeexitrrrrfs\(            (ErQ