#
# SOAP SERVER
# $Id$
#
# a simple SOAP server for Python
#
# History:
# 1999-02-01 fl  added to xmlrpclib distribution 
# 2000-05-26 fl  adapted for SOAP 
# 2000-06-17 fl  fixed error codes
#
# written by Fredrik Lundh, January 1999.
#
# Copyright (c) 1999-2000 by Secret Labs AB.
# Copyright (c) 1999-2000 by Fredrik Lundh.
#
# fredrik@pythonware.com
# http://www.pythonware.com
#
# --------------------------------------------------------------------
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted.  This software is provided as is.
# --------------------------------------------------------------------
#

import SocketServer, BaseHTTPServer
import soaplib
import sys

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_POST(self):
        try:
	    # get arguments
            data = self.rfile.read(int(self.headers["content-length"]))
            method, params = soaplib.loads(data)

	    # generate response
	    try:
		response = self.call(method, params)
	    except:
		# report exception back to server
		response = soaplib.dumps(
		    soaplib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value))
		    )
		status = 500
	    else:
		response = soaplib.dumps(
		    soaplib.Response(method, None, response), 1
		    )
		status = 200
        except:
	    # internal error, report as HTTP server error
	    self.send_response(500)
	    self.end_headers()
	else:
	    # got a valid SOAP response
	    self.send_response(status)
	    self.send_header("Content-type", "text/xml")
	    self.send_header("Content-length", str(len(response)))
	    self.end_headers()
	    self.wfile.write(response)

	    # shut down the connection (from Skip Montanaro)
	    self.wfile.flush()
	    self.connection.shutdown(1)

    def call(self, method, params):
	# override this method to implement RPC methods
	print "CALL", method, params
	if method == "quit":
	    import os
	    os._exit(1) # may cause socket errors on the client site
	if method == "exception":
	    raise TypeError, "some python exception"
	return params # echo

if __name__ == "__main__":
    port = 8000
    server = SocketServer.TCPServer(('', port), RequestHandler)
    print "listening on port", port
    server.serve_forever()
