"""quixote.util

Contains various useful functions:

  xmlrpc(request, func) : Processes the body of an XML-RPC request, and calls
                          'func' with the method name and parameters.
"""

# created 2002/03/29, AMK

__revision__ = "$Id: util.py,v 1.2 2002/09/09 16:06:23 akuchlin Exp $"

import sys, xmlrpclib

def xmlrpc (request, func):
    """xmlrpc(request:Request, func:callable) : string

    Processes the body of an XML-RPC request, and calls 'func' with
    two arguments, a string containing the method name and a tuple of 
    parameters.  
    """
    
    # Get contents of POST body
    method = request.environ['REQUEST_METHOD'] 
    if method != 'POST':
        raise RuntimeError, ('XML-RPC handler cannot accept HTTP request '
                             'method %r' % method)
    
    length = int(request.environ['CONTENT_LENGTH'])
    data = request.stdin.read(length)

    # Parse arguments
    params, method = xmlrpclib.loads(data)

    try:
        result = func(method, params)
    except xmlrpclib.Fault, exc:
        result = exc
    except:
        # report exception back to client
        result = xmlrpclib.dumps(
            xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value))
            )
    else:
        result = (result,)
        result = xmlrpclib.dumps(result, methodresponse=1)
        
    request.response.set_header('content-type', 'text/xml')
    return result
