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