Python | XMLRPC : EXPOSING METHODS OF OBJECTS, DISPATCHING CALLS YOURSELF & INTROSPECTION API














































Python | XMLRPC : EXPOSING METHODS OF OBJECTS, DISPATCHING CALLS YOURSELF & INTROSPECTION API



----- Exposing Methods of Objects -----

The earlier sections talked about techniques for establishing APIs using good naming conventions and namespacing. Another way to incorporate namespacing into an API is to use instances of classes and expose their methods. The first example can be recreated using an instance with a single method.


A client can call the method directly:


and receive output like:



We have lost the dir. prefix for the service, though, so let us
define a class to let us set up a service tree that can be invoked from
clients.



By registering the instance of ServiceRoot with allow_dotted_names
enabled, we give the server permission to walk the tree of objects when a
request comes in to find the named method using getattr().




----- Dispatching Calls Yourself -----

By default, register_instance() finds all callable attributes of the instance with names not starting with '_' and registers them with their name. If you want to be more careful about the exposed methods, you could provide your own dispatching logic. For example:



The public() method of MyService is marked as exposed to the XML-RPC service while private() is not. The _dispatch() method is invoked when the client tries to access a function that is part of MyService. It first enforces the use of a prefix (%u201Cprefix.%u201D in this case, but you can use any string). Then it requires the function to have an attribute called exposed with a true value. The exposed flag is set on a function using a decorator for convenience.


Here are a few sample client calls:


and the resulting output, with the expected error messages trapped and reported:



There are several other ways to override the dispatching mechanism, including subclassing directly from SimpleXMLRPCServer. Check out the docstrings in the module for more details.

----- Introspection API -----

As with many network services, it is possible to query an XML-RPC server to ask it what methods it supports and learn how to use them. SimpleXMLRPCServer includes a set of public methods for performing this introspection. By default they are turned off, but can be enabled with register_introspection_functions(). You can add explicit support for system.listMethods() and system.methodHelp() by defining _listMethods() and _methodHelp() on your service class. For example,