Python JSON POST请求 [英] Python JSON POST request

查看:186
本文介绍了Python JSON POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不同的问题:1个脚本。我必须从一个Python脚本中获取JSON-ify,该脚本将在客户端运行并在远程URL上执行POST。我在这里关注文档 http://docs.python.org/2/library/httplib .html - 但是,我不确定我做得对。当我在Mac上运行它时,我没有得到任何响应状态。现在,我怀疑以下内容 -

Different questions re: 1 script. I have to JSON-ify from a Python script that'll run on client-side and do a POST on a remote URL. I am following the docs here http://docs.python.org/2/library/httplib.html - However, I am not sure if I am doing it right. I am not getting any response-status either when I run it on my Mac. Right now, I have doubts about the following -

(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. 

我强烈感觉我的错误超出了此列表。

I have a strong feeling that my errors extend beyond this list.

提前致谢。

import psutil 
import socket
import time
import sample
import json
import httplib
import urllib



serverHost = sample.host
port = sample.port

thisClient = socket.gethostname()
cpuStats = psutil.cpu_times_percent(percpu=True)
print cpuStats


currentTime = int(time.time())
s = socket.socket()
s.connect((serverHost,port))



cpuStatsjson = json.dumps(cpuStats._asdict())
params = urllib.urlencode({'cpuStats': cpuStats, 'device_key': 12345})
headers = {"Content-type": "application/json", "Accept": "text/plain"}
conn = httplib.HTTPConnection("http://XXX.XXX.XXX.XXX:YYYY")
conn.request("POST", "", cpuStatsjson, headers)
response = conn.getresponse()
print response.status, response.reason

s.close()


推荐答案

是的,httplib可能会这样做,但我强烈建议像 request

Yes, httplib can do this probably, but I would strongly suggest something like requests

此问题适用于请求

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)

至于你的代码,我不需要套接字连接,以下代码确实为我发布:

as for your code, the socket connection is not needed I guess and the following code does post for me:

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)

这篇关于Python JSON POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆