I have created a local server which sends a HTTP POST message to http://httpbin.org/post and then prints the return message on the screen.
The python CGI code that runs at the back end prints the return message in a 'pretty' format when run directly from the terminal:
Content-type:text/html
<html>
<head>
<title>TEST</title>
<meta http-equiv='refresh' content='1'>
</head>
<body>
<h2>RETURN: </h2><h5>{
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"Accept": "*/*",
"Connection": "close",
"Accept-Encoding": "gzip, deflate, compress",
"User-Agent": "python-requests/1.2.0 CPython/2.7.3 Linux/3.5.0-17-generic",
"Content-Length": "67"
},
"files": {},
"origin": "125.63.99.141",
"args": {},
"url": "http://httpbin.org/post",
"data": "",
"form": {
"RAM": "2577.46",
"TIME": "2013-05-20 21:36:16.388751",
"TEMP": "+55.5\u00b0C"
},
"json": null
}</h5>
</body>
</html>
However, when the code is run through the local server using CGI, the message is badly formatted (all in one line):
{ "headers": { "Accept": "*/*", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "Accept-Encoding": "gzip, deflate, compress", "Content-Length": "60", "User-Agent": "python-requests/1.2.0 CPython/2.7.3 Linux/3.5.0-17-generic", "Connection": "close" }, "args": {}, "url": "http://httpbin.org/post", "data": "", "origin": "125.63.99.141", "form": { "TEMP": "+55.5", "TIME": "2013-05-20 21:57:38.973723", "RAM": "2478.78" }, "json": null, "files": {} }
I'm new to HTML and JSON but I think that there could be a way to store the response as a JSON object and then use some HTML tags to print it in a formatted manner.
This is my CGI file:
#!/usr/bin/python
import requests
import subprocess
from datetime import datetime
# script to extract free RAM from vmstat
str = "vmstat | awk '/[0-9]/ { print $4/1024 }'"
# script to extract CPU core temp from sensors
temp = "sensors | grep temp | awk '{print $2}'"
# run script and store output
p=subprocess.Popen(str, shell=True,stdout=subprocess.PIPE)
out, err = p.communicate()
p=subprocess.Popen(temp, shell=True,stdout=subprocess.PIPE)
out2, err2 = p.communicate()
# create dataload
ram = out.rstrip()
time = datetime.now()
temp = out2.rstrip()
payload = {'RAM':ram, 'TEMP':temp, 'TIME':time}
#print payload
# send HTTP POST request
r = requests.post('http://httpbin.org/post', data=payload)
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>TEST</title>"
print "<meta http-equiv='refresh' content='1'>"
print "</head>"
print "<body>"
print "<h2>RETURN: %s</h2>" % (r.text)
print "</body>"
print "</html>"