64ceb9904e9155a23689620d9a12f9e1e548a2c9
[sfa.git] / sfa / server / modpythonapi / ModPython.py
1 #
2 # Apache mod_python interface
3 #
4 # Aaron Klingaman <alk@absarokasoft.com>
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 #
7 # Copyright (C) 2004-2006 The Trustees of Princeton University
8 #
9
10 import sys
11 import traceback
12 import xmlrpclib
13 from mod_python import apache
14
15 from API import RemoteApi
16 api = RemoteApi()
17
18 class unbuffered:
19     """\r
20     Write to /var/log/httpd/error_log. See\r
21 \r
22     http://www.modpython.org/FAQ/faqw.py?req=edit&file=faq02.003.htp\r
23     """\r
24 \r
25     def write(self, data):\r
26         sys.stderr.write(data)\r
27         sys.stderr.flush()\r
28 \r
29 #log = unbuffered()
30
31 def handler(req):
32     try:
33         if req.method != "POST":
34             req.content_type = "text/html"
35             req.send_http_header()
36             req.write("""
37 <html><head>
38 <title>PLCAPI XML-RPC/SOAP Interface</title>
39 </head><body>
40 <h1>PLCAPI XML-RPC/SOAP Interface</h1>
41 <p>Please use XML-RPC or SOAP to access the PLCAPI.</p>
42 </body></html>
43 """)
44             return apache.OK
45
46         # Read request
47         request = req.read(int(req.headers_in['content-length']))
48
49         # mod_python < 3.2: The IP address portion of remote_addr is
50         # incorrect (always 0.0.0.0) when IPv6 is enabled.
51         # http://issues.apache.org/jira/browse/MODPYTHON-64?page=all
52         (remote_ip, remote_port) = req.connection.remote_addr
53         remote_addr = (req.connection.remote_ip, remote_port)
54
55         # Handle request
56         response = api.handle(remote_addr, request)
57
58         # Write response
59         req.content_type = "text/xml; charset=" + api.encoding
60         req.send_http_header()
61         req.write(response)
62
63         return apache.OK
64
65     except Exception, err:
66         # Log error in /var/log/httpd/(ssl_)?error_log
67         print >> log, err, traceback.format_exc()
68         return apache.HTTP_INTERNAL_SERVER_ERROR