2013-05-20 73 views
0

我創建了一個本地服務器,它將HTTP POST消息發送到http://httpbin.org/post,然後在屏幕上輸出返回消息。使用CGI(Python)在HTML中顯示HTTP響應消息

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代碼打印在一個「漂亮」格式返回消息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>" 

回答

0

而不是<h2>包裝輸出,敷在<pre>。這將保持你的換行符完好無損。

+0

謝謝,這個伎倆。 – vinayakshukl