Python CGI Debugging Helper Script

I’m currently trying to move a small php app that I wrote to python and leverage the power of tools like SQLAlchemy and Flask. Since I only rented a small hosting package, I can’t run the python app directly on the server, but I need to use the servers cgi-bin, which is a special directory for executable scripts that can be used to create a website.

During development, I ran into some problems with my database connection. For the debugging of these, I needed access to the output of my script, which for example contains a stacktrace, but my hosting provider does only grand me access to these via a website that will show the entire error log of the last five days and thus contains a lot of unneeded information and is hard to read. To make my life a bit easier, I wrote myself the following script:

#! .venv/bin/python3
import sys
import subprocess
import socket
from markupsafe import escape

subscript = ['./my_actual_cgi_script.py']
result = subprocess.run(subscript, capture_output=True)

print("Content-Type: text/html")
print()
print("<html><body>")
print("<h1>Python CGI Debugging Helper</h1>")
print("<p>")
print(f"Host name: {socket.gethostname()}</br>")
print(f"Call of this script: {sys.argv}</br>")
print(f"Sub-script call: {subscript}</br>")
print("</p>")
print("<h2>Exception:</h2>")
try:
    result.check_returncode()
except Exception as error:
    print(f"<pre>\n{error}\n</pre>")
else:
    print("<p>(None)</p>")
stdout = escape(result.stdout.decode())
stderr = escape(result.stderr.decode())
print(f"<h2>Std-Out:</h2>\n<pre>\n{stdout}\n</pre>")
print(f"<h2>Std-Err:</h2>\n<pre>\n{stderr}\n</pre>")
print("</body></html>")

This needs to be marked as executable and put directly next to the actual script my_actual_cgi_script.py. When called, it will then run this script in a subprocess and print the full output of the script in a well formatted way, that makes debugging a lot more comfortable.

coding_structure

A blog by Timo Dreyer


2021-05-16