Revision 4 as of 2005-07-04 02:31:40

Clear message

This is an "automatic DocXmlRpcServer." There is also a CGI variant: AutoXmlRpcCgi.

TableOfContents()

Tutorial

Suppose you have a Python module:

   1 def spam():
   2     return "spam"

How can you share that on [http://www.irchelp.org/ IRC?]

Mark it like this:

   1 XMLRPC_namespace = "eggs"
   2 
   3 def spam():
   4     return "spam"

Now, just run the AutoXmlRpcServer from that directory, and you're done!

$ ./xrserver.py
Sat Apr 16 21:29:24 2005 Application Starting.

You're XML-RPC server's up and running, port 8000.

Your friends can now call your function!

   1 import xmlrpclib
   2 
   3 server = xmlrpclib.ServerProxy("http://example.com:8000/")
   4 print server.eggs.spam()

There it is!

Notes

Code: xrserver.py

   1 #!/usr/bin/env python
   2 """Serve specially marked modules by XML-RPC.
   3 
   4   -Hhostname   host name, default ""
   5   -Pportnum    port number, default 8000
   6 
   7 This script starts an XML-RPC server, and publishes auto-detected
   8 modules from the working directory.
   9 
  10 Functions within Modules that define the name "XMLRPC_namespace" are
  11 published. Function names that begin with an underscore (ex: _eggs) are
  12 not published. Functions are published within the XML-RPC namespace
  13 designated by the XMLRPC_namespace value, or the base namespace if the
  14 value is None.
  15 """
  16 
  17 import time
  18 import os
  19 import sets
  20 import imp
  21 import types
  22 
  23 import optparse
  24 import DocXMLRPCServer
  25 
  26 
  27 def find_modules(path="."):
  28     """Return names of modules in a directory.
  29 
  30     Returns module names in a list. Filenames that end in ".py" or
  31     ".pyc" are considered to be modules. The extension is not included
  32     in the returned list.
  33     """
  34     modules = sets.Set()
  35     for filename in os.listdir(path):
  36         module = None
  37         if filename.endswith(".py"):
  38             module = filename[:-3]
  39         elif filename.endswith(".pyc"):
  40             module = filename[:-4]
  41         if module is not None:
  42             modules.add(module)
  43     return list(modules)
  44 
  45 
  46 def load_module(name, path=["."]):
  47     """Return a named module found in a given path."""
  48     (file, pathname, description) = imp.find_module(name, path)
  49     return imp.load_module(name, file, pathname, description)
  50 
  51 
  52 def find_xmlrpc_modules():
  53     """Find modules that define XMLRPC_namespace.
  54 
  55     Loads all modules in the current working directory. Returns a list
  56     of modules, the modules that define XMLRPC_namespace.
  57     """
  58     modules = [load_module(m) for m in find_modules()]
  59     xmlrpc_modules = []
  60     for m in modules:
  61         if m.__dict__.has_key("XMLRPC_namespace"):
  62             xmlrpc_modules.append(m)
  63     return xmlrpc_modules
  64 
  65 
  66 def functions_in_module(module):
  67     """Find all functions in a module."""
  68     functions = []
  69     for obj in module.__dict__.values():
  70         if isinstance(obj, types.FunctionType):
  71             functions.append(obj)
  72     return functions
  73 
  74 
  75 if __name__ == "__main__":
  76     parser = optparse.OptionParser(__doc__)
  77     parser.add_option("-H", "--host", dest="hostname",
  78                       default="127.0.0.1", type="string",
  79                       help="specify hostname to run on")
  80     parser.add_option("-p", "--port", dest="portnum", default=8000,
  81                       type="int", help="port number to run on")
  82 
  83     (options, args) = parser.parse_args()
  84     if len(args) != 0:
  85         parser.error("incorrect number of arguments")
  86 
  87     ServerClass = DocXMLRPCServer.DocXMLRPCServer
  88     server = ServerClass((options.hostname, options.portnum),
  89                          logRequests=0)
  90 
  91     for module in find_xmlrpc_modules():
  92         for func in functions_in_module(module):
  93             if func.__name__.startswith("_"):
  94                 continue
  95             full_name = func.__name__
  96             if module.XMLRPC_namespace is not None:
  97                 full_name = "%s.%s" % (module.XMLRPC_namespace,
  98                                        full_name)
  99             server.register_function(func, full_name)
 100 
 101     server.set_server_title("xrserver")
 102     server.register_introspection_functions()
 103 
 104     print time.asctime(), 'Application Starting.'
 105     server.serve_forever()
 106     print time.asctime(), 'Application Finishing.'

Discussion

This could be improved. Some ideas:

-- LionKimbro DateTime(2005-04-17T05:51:41Z)

Unable to edit the page? See the FrontPage for instructions.