Fix version output when missing.
[plcapi.git] / ModPythonJson.py
1 #
2 # Apache mod_python interface for JSON requests
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 # $Id$
9 # $URL$
10 #
11
12 import sys
13 import traceback
14 import xmlrpclib
15 from mod_python import apache
16
17 from PLC.Debug import log
18
19 from PLC.API import PLCAPI
20 api = PLCAPI()
21
22 def handler(req):
23     try:
24         if req.method != "POST":
25             req.content_type = "text/html"
26             req.send_http_header()
27             req.write("""
28 <html><head>
29 <title>PLCAPI JSON Interface</title>
30 </head><body>
31 <h1>PLCAPI JSON Interface</h1>
32 <p>Please POST JSON to access the PLCAPI.</p>
33 </body></html>
34 """)
35             return apache.OK
36
37         # Read request
38         request = req.read(int(req.headers_in['content-length']))
39
40         # mod_python < 3.2: The IP address portion of remote_addr is
41         # incorrect (always 0.0.0.0) when IPv6 is enabled.
42         # http://issues.apache.org/jira/browse/MODPYTHON-64?page=all
43         (remote_ip, remote_port) = req.connection.remote_addr
44         remote_addr = (req.connection.remote_ip, remote_port)
45
46         # Handle request
47         response = api.handle_json(remote_addr, request)
48
49         # Shut down database connection, otherwise up to MaxClients DB
50         # connections will remain open.
51         api.db.close()
52
53         # Write response
54         req.content_type = "text/json; charset=" + api.encoding
55         req.send_http_header()
56         req.write(response)
57
58         return apache.OK
59
60     except Exception, err:
61         # Log error in /var/log/httpd/(ssl_)?error_log
62         print >> log, err, traceback.format_exc()
63         return apache.HTTP_INTERNAL_SERVER_ERROR