简体   繁体   English

使用Python JSON的HTTP Post请求

[英]HTTP Post request with Python JSON

I am trying to send data to a URL. 我正在尝试将数据发送到URL。 I've a code to send it for each cpu on my Mac. 我有一个代码可以为我的Mac上的每个cpu发送它。 But the current code loops through each of the cpustats and sends them 1 after the other. 但是当前的代码循环遍历每个cpustats并将它们一个接一个地发送。 I need to send all of them in 1 POST 'cycle' but it should be formatted such that it sends it like this - 我需要在1个POST'循环'中发送所有这些,但它应格式化,以便它像这样发送 -

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

and so on... 等等...

Further, the current code pulls the stats from my Mac (with a '200 OK' for each cpustat) but when I run it on Linux, Windows, it just returns the prompt without giving any errors or stats. 此外,当前代码从我的Mac中提取统计数据(每个cpustat都有'200 OK')但是当我在Linux,Windows上运行它时,它只返回提示而不给出任何错误或统计信息。 My guess is that it has to do with the 'break' at 'socket.error:' (My Mac has 4 cpus but the Linux and Windows machines on which I test it have 1 each. 我的猜测是它与'socket.error:'中的'break'有关(我的Mac有4个cpus,但我测试它的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()

If you're just trying to send the data all at once you should realize that you're not actually sending a dictionary across, but instead you're sending a string. 如果您只是尝试一次性发送数据,您应该意识到您实际上并没有发送字典,而是发送字符串。 In that case, you could easily send all the data in one go by just constructing your data like so: 在这种情况下,您只需构建数据就可以轻松地一次性发送所有数据:

data = "\n".join([json.dumps(stat._asdict()) for stat in cpuStats])

If that endpoint is someone else's that might not be sensible, but assuming that's your own endpoint you're pointing at it should be pretty trivial to unbundle this data. 如果该端点是其他可能不合理的端点,但假设您自己的端点指向它,那么解开这些数据应该是非常简单的。

Additionally I would HIGHLY suggest switching to the requests module over urllib as it extends all of the same functionality in a MUCH easier wrapper. 另外,我强烈建议通过urllib切换到requests模块,因为它在更容易的包装器中扩展了所有相同的功能。 For instance, in requests you would send that request by doing the following: 例如,在requests您将通过执行以下操作发送该请求:

import requests

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM