Python JSON POST请求

Python JSON POST请求,python,json,http,post,httplib,Python,Json,Http,Post,Httplib,不同的问题:1脚本。我必须从将在客户端运行的Python脚本中获取JSON信息,并在远程URL上发布帖子。我遵循这里的文档-但是,我不确定我是否做对了。当我在Mac上运行它时,我也没有得到任何响应状态。现在,我对以下几点表示怀疑: (1) The dummy 'device_key' (of the client) (2) The IP, Port listed at HTTPConnection --- I don't want to hard-code the IP, Port - sho

不同的问题:1脚本。我必须从将在客户端运行的Python脚本中获取JSON信息,并在远程URL上发布帖子。我遵循这里的文档-但是,我不确定我是否做对了。当我在Mac上运行它时,我也没有得到任何响应状态。现在,我对以下几点表示怀疑:

(1) The dummy 'device_key' (of the client) 
(2) The IP, Port listed at HTTPConnection --- I don't want to hard-code the IP, Port - should I be using "ServerHost:Port"
(3) The cpuStats is a nametuple (of 'user'= somevalue, 'idle' = somevalue, etc.) that is converted to a dict by _asdict(). I want to just send the cpuStats (namedtuple) to the URLpage.
(4) The cpu_times_percent(percpu=True) is what the docs say <http://code.google.com/p/psutil/wiki/Documentation#CPU> but when I run the script on my Mac - it shows just 1 namedtuple of cpu percentages though my mac has 4 cpus. 

是的,httplib可能可以做到这一点,但我强烈建议

使此问题在请求中起作用

import requests

def post_some_dict(dict):
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    r = requests.post(url, data=json.dumps(dict), headers=headers)
至于您的代码,我想不需要套接字连接,下面的代码确实为我发布了:

data = {"somekey": 12}
headers = {"Content-type": "application/json", "Accept": "text/plain"}
conn = httplib.HTTPConnection('xx.xx.xx.xx')
conn.request("POST", "/", json.dumps(data), headers)

是的,httplib可能可以做到这一点,但我强烈建议

使此问题在请求中起作用

import requests

def post_some_dict(dict):
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    r = requests.post(url, data=json.dumps(dict), headers=headers)
至于您的代码,我想不需要套接字连接,下面的代码确实为我发布了:

data = {"somekey": 12}
headers = {"Content-type": "application/json", "Accept": "text/plain"}
conn = httplib.HTTPConnection('xx.xx.xx.xx')
conn.request("POST", "/", json.dumps(data), headers)

要求是避免使用第三方库,因此我使用urllib、httplib。请注意,
请求
现在直接接受Python数据结构进行编码(这里使用
json=dict
,无需使用
json.dumps()
,还为您设置了正确的
内容类型
头)。另外,不要使用
dict
作为变量名,你在隐藏内置类型。是的,隐藏确实不太好,我同意。我不知道请求现在接受DICT作为JSON结构,真的很好!要求是避免使用第三方库,因此我使用urllib、httplib。请注意,
请求
现在直接接受Python数据结构进行编码(这里使用
json=dict
,无需使用
json.dumps()
,还为您设置了正确的
内容类型
头)。另外,不要使用
dict
作为变量名,你在隐藏内置类型。是的,隐藏确实不太好,我同意。我不知道请求现在接受DICT作为JSON结构,真的很好!