Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python JSON的HTTP Post请求_Python_Json_Post - Fatal编程技术网

使用Python JSON的HTTP Post请求

使用Python JSON的HTTP Post请求,python,json,post,Python,Json,Post,我正在尝试将数据发送到URL。我有一个代码为我的Mac上的每个cpu发送它。但是当前的代码循环通过每个cpustat,并依次发送它们。我需要在一个“周期”后发送所有邮件,但其格式应确保其发送方式如下- cpuStats = {nice: 123.0, idle:123.0....} cpuStats = {nice: 123.0, idle:123.0....} cpuStats = {nice: 123.0, idle:123.0....} 等等 此外,当前代码从我的Mac上获取统计数据(每

我正在尝试将数据发送到URL。我有一个代码为我的Mac上的每个cpu发送它。但是当前的代码循环通过每个cpustat,并依次发送它们。我需要在一个“周期”后发送所有邮件,但其格式应确保其发送方式如下-

cpuStats = {nice: 123.0, idle:123.0....}
cpuStats = {nice: 123.0, idle:123.0....}
cpuStats = {nice: 123.0, idle:123.0....}
等等

此外,当前代码从我的Mac上获取统计数据(每个cpustat都有一个“200OK”),但当我在Linux、Windows上运行它时,它只返回提示,而没有给出任何错误或统计数据。我的猜测是,这与“socket.error:”的“break”有关(我的Mac有4个CPU,但我测试它的Linux和Windows机器各有1个)

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():
    global cpuStats
    for stat in cpuStats:
        stat = json.dumps(stat._asdict())

        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': stat, 'thisClient': 1234})
            headers = headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
            conn = httplib.HTTPConnection(serverHost, port)
            conn.request("POST", "", params, headers)
            response = conn.getresponse()
            print response.status, response.reason

        except IndexError:
            continue
        except socket.error:
            print "Connection refused"
            continue

    print stat

loop_thru_cpus()
s.close()

如果您只是试图一次发送所有数据,您应该意识到您实际上并不是在发送字典,而是在发送字符串。在这种情况下,您可以通过如下方式构造数据,轻松地一次性发送所有数据:

data = "\n".join([json.dumps(stat._asdict()) for stat in cpuStats])
如果该端点是其他人的端点,这可能是不明智的,但假设您指向的是您自己的端点,那么分解这些数据应该非常简单

此外,我强烈建议通过urllib切换到
请求
模块,因为它在一个更简单的包装器中扩展了所有相同的功能。例如,在
请求
中,您可以通过执行以下操作发送该请求:

import requests

response = requests.post("your://url.here", data=data)
print response.content

您是想一次发送包含所有数据的帖子,还是想一次发送四个帖子请求?@SlaterTyranus,应该是第一个one@SlaterTyranus-我只需发送一个POST请求,其中包括所有的cpu.Thx。我必须使用内置库,因此不使用“请求”。统计信息将发布在服务器上其他人也使用的版本,因此我必须以这种格式发送它。如果有帮助,下面是我得到的说明-“一个参数行params=urllib.urlencode({'cpuStats':statJson,'deviceKey':1234})应该为每个cpu重复具有适当值的cpuStats,并且不应该再次发送请求。这都应该是单个http POST请求的一部分。“@user2480526实际上与此响应一致。