我在这方面花了很多时间,但似乎仍然无法让它发挥作用。任务是 - 我必须将系统统计信息发送到一个 URL,并且脚本应该将其拉出,转换机器的每个 cpu 统计信息的 namedtuple,然后将它们全部作为 JSON 发送到 1 个单个 POST 请求中。发送数据后,必须关闭连接。
对于“1 个单一的 POST 请求”功能,我在脚本中添加了后一个函数 (senddata_to_server)。没有它(连接详细信息只是简单地列在那里而没有函数),当我在 Mac/Windows/Linux 上运行它时,它曾经以 1 的方式返回所有命名元组,然后返回“200 OK”,然后继续打印“连接”永远拒绝。现在当我运行它时,它只是挂在那里而不返回任何东西。
(我之前已经问过这个问题( HTTP Post request with Python JSON ),但我需要在循环内有'params',在它之外有连接细节。
import psutil
import socket
import time
import sample
import json
import httplib
import urllib
serverHost = sample.host
port = sample.port
thisClient = socket.gethostname()
currentTime = int(time.time())
s = socket.socket()
s.connect((serverHost, port))
cpuStats = psutil.cpu_times_percent(percpu=True)
def loop_thru_cpus():
while True:
global cpuStats
cpuStats = "/n".join([json.dumps(stats._asdict()) for stats in cpuStats])
try:
command = 'put cpu.usr ' + str(currentTime) + " " + str(cpuStats[0]) + "host ="+thisClient+ "/n"
s.sendall(command)
command = 'put cpu.nice ' + str(currentTime) + " " + str(cpuStats[1]) + "host ="+ thisClient+ "/n"
s.sendall(command)
command = 'put cpu.sys ' + str(currentTime) + " " + str(cpuStats[2]) + "host ="+ thisClient+ "/n"
s.sendall(command)
command = 'put cpu.idle ' + str(currentTime) + " " + str(cpuStats[3]) + "host ="+ thisClient+ "/n"
s.sendall(command)
params = urllib.urlencode({'cpuStats': cpuStats, 'deviceKey': 1234, 'timeStamp': str(currentTime)})
return params
print cpuStats
except IndexError:
continue
except socket.error:
print "Connection refused"
continue
finally:
s.close()
def senddata_to_server():
x = loop_thru_cpus()
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
conn = httplib.HTTPConnection(serverHost, port)
conn.request = ("POST", "", x.params, headers)
response = conn.response()
print response.status, response. reason
print x.cpuStats
conn.close()
loop_thru_cpus()
senddata_to_server()