【发布时间】:2013-05-20 16:31:24
【问题描述】:
我创建了一个本地服务器,它向http://httpbin.org/post 发送 HTTP 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>"
【问题讨论】:
标签: python html http format cgi