0

さまざまな質問: 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()
4

1 に答える 1

5

はい、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)
于 2013-09-10T00:57:17.593 に答える