无效的JSON:使用python套接字在CouchDB中未定义

时间:2017-03-27 20:23:54

标签: python json couchdb

我编写了这个python脚本,该脚本应该将一个http请求组成一个字符串并将其发送到连接到couchDB的套接字上:

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请求字符串中,因为完全相同的查询与Postman一起工​​作正常,但我无法弄清楚问题。

1 个答案:

答案 0 :(得分: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