[英]Display HTTP Response Message in HTML using CGI (Python)
我创建了一个本地服务器,该服务器将HTTP POST消息发送到http://httpbin.org/post ,然后在屏幕上打印返回消息。
直接从终端运行时,在后端运行的python CGI代码以“漂亮”格式打印返回消息:
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>
但是,当使用CGI在本地服务器上运行代码时,消息格式错误(全部在一行中):
{ "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": {} }
我是HTML和JSON的新手,但我认为可能存在一种将响应存储为JSON对象,然后使用一些HTML标记以格式化方式打印响应的方法。
这是我的CGI文件:
#!/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>"
而不是将输出包装在<h2>
,而是将其包装在<pre>
。 这样可以使您的换行符保持完整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.