【问题标题】:Python JSON POST requestPython JSON POST 请求
【发布时间】:2013-09-09 23:33:33
【问题描述】:

不同的问题:1 个脚本。我必须从将在客户端运行并在远程 URL 上执行 POST 的 Python 脚本进行 JSON 化。我正在关注这里的文档http://docs.python.org/2/library/httplib.html - 但是,我不确定我是否做得对。当我在我的 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. 

我有一种强烈的感觉,我的错误超出了这个列表。

提前致谢。

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

【问题讨论】:

    标签: python json http post httplib


    【解决方案1】:

    是的,httplib 可能可以做到这一点,但我强烈建议像 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)
    

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

    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)
    

    【讨论】:

    • 要求是避免使用 3rd 方库,因此,我使用的是 urllib、httplib。
    • 请注意,requests 现在直接接受 Python 数据结构进行编码(此处使用json=dict,无需使用json.dumps(),还为您设置了正确的Content-Type 标头)。另外,不要使用dict 作为变量名,你会隐藏内置类型。
    • 是的,阴影确实不太好,我必须同意。我不知道 requests 现在接受 dicts 作为 JSON 结构,确实非常好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    相关资源
    最近更新 更多