as a comment in plc.wsgi: keep track of potentially useful debug snippet
[plcapi.git] / apache / plc.wsgi
1 # -*- python -*-
2 #
3 # Apache mod_wsgi python interface
4 #
5 # Copyright (C) 2004-2006 The Trustees of Princeton University
6 #
7
8 import sys
9 sys.path.append('/usr/share/plc_api')
10 sys.stdout = sys.stderr
11 import traceback
12 from PLC.Logger import logger
13 from PLC.API import PLCAPI
14
15 def application(environ, start_response):
16     try:
17         status = '200 OK'
18         if environ.get('REQUEST_METHOD') != 'POST':
19             content_type = 'text/html; charset=utf-8'
20             output = """
21 <html><head>
22 <title>PLCAPI WSGI XML-RPC/SOAP Interface</title>
23 </head><body>
24 <h1>PLCAPI WSGI XML-RPC/SOAP Interface</h1>
25 <p>Please use XML-RPC or SOAP to access the PLCAPI.</p>
26 <p>At the very least you need to use a POST method.</p>
27 </body></html>
28 """
29         else:
30             # Thomas Dreibholz <dreibh@simula.no>
31             # Note that this function is called within multiple threads!
32             # "api" MUST be a local variable instead of a global one.
33             # Otherwise, this causes concurrent accesses to the same
34             # object within different threads!
35             api = PLCAPI()
36             api.environ = environ
37             content_type = 'text/xml; charset=utf-8'
38             ip = environ.get('REMOTE_ADDR')
39             port = environ.get('REMOTE_PORT')
40             output = api.handle((ip,port),  environ.get('wsgi.input').read())
41 # uncomment for debug
42 #            try:
43 #                with open("/tmp/dbgplc.log", "a") as f:
44 #                    print(f"{ip=} {port=}\n"
45 #                          f"{output=}",
46 #                          file=f)
47 #            except Exception as exc:
48 #                pass
49             # Shut down database connection, otherwise up to MaxClients DB
50             # connections will remain open.
51             api.db.close()
52     except Exception as err:
53         status = '500 Internal Server Error'
54         content_type = 'text/html; charset=utf-8'
55         output = 'Internal Server Error'
56         logger.exception("INTERNAL ERROR !!")
57
58     # Write response
59     # with python3 wsgi expects a bytes object here
60     output = output.encode()
61     response_headers = [('Content-type', '%s' % content_type),
62                        ('Content-Length', str(len(output)))]
63     start_response(status, response_headers)
64     return [output]