2017-03-27 56 views
0

我寫這個python腳本應該組成一個http請求作爲一個字符串,並將其發送連接到CouchDB的一個插座上:無效的JSON:未定義CouchDB中使用python插槽

import socket 
import json 

DB_IP = '127.0.0.1' 
DB_PORT = 5984 

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

sock.connect((DB_IP, DB_PORT)) 

db_name = 'temperatures' 
doc_id = 'today' 

request = "PUT /" + db_name + "/" + doc_id + " HTTP/1.1\n" 
request += "Content-Type: application/json\n\n" 
request += json.dumps({'min_t': 10, 'max_t': 20}) 

sock.sendall(request) 

result = sock.recv(4096) 

print result 

輸出爲:

HTTP/1.1 400 Bad Request 
Server: CouchDB/1.6.1 (Erlang OTP/19) 
Date: Mon, 27 Mar 2017 20:07:04 GMT 
Content-Type: text/plain; charset=utf-8 
Content-Length: 48 
Cache-Control: must-revalidate 

CouchDB的日誌:

[debug] [<0.575.0>] 'PUT' /temperatures/today {1,1} from "127.0.0.1" 
Headers: [{'Content-Type',"application/json"}] 
[debug] [<0.575.0>] OAuth Params: [] 
[error] [<0.575.0>] attempted upload of invalid JSON (set log_level to debug to log it) 
[debug] [<0.575.0>] Invalid JSON: undefined 
[info] [<0.575.0>] 127.0.0.1 - - PUT /temperatures/today 400 
[debug] [<0.575.0>] httpd 400 error response: 
{"error":"bad_request","reason":"invalid_json"} 

我敢打賭錯誤是在HTTP請求字符串,因爲確切的SA我的查詢與郵差工作正常,但我無法找出問題。

回答

0

您需要包含內容長度標頭,因爲看起來CouchDB無法猜測您的JSON正文的長度。

json_data = '{"min_t": 10, "max_t": 20}' 
request = "PUT /" + db_name + "/" + doc_id + " HTTP/1.1\n" 
request += "Accept: application/json\n" 
request += "Content-Length: " + str(len(json_data)) + "\n" 
request += "Content-Type: application/json\n\n" 
request += json_data