Python - 使用httplib发送JSON数据
我正在尝试在tastypie-Django的Python应用中用JSON数据进行一个简单的PUT请求。但是,当我通过代码调用时,出现了401错误响应,而当我在终端执行cURL命令时却没有错误。我的代码是:
data_to_update = json.dumps({ "NAME" : username,
"type": mytype
})
headers = { "Content-type": "application/json",
"Authorization: ApiKey": '{0}:{1}'.format(username, key)
}
conn = httplib.HTTPConnection('localhost:8000')
conn.set_debuglevel(1)
conn.request('PUT', '/api/v1/table/1/', data_to_update, headers=headers)
response = conn.getresponse()
print response.status, response.reason
conn.close()
然后我看到的输出是:
send: u'PUT /api/v1/table/10/ HTTP/1.1\r\nHost: localhost:8000\r\nAccept-Encoding: identity\r\nContent-Length: 148\r\nContent-type: application/json\r\nAuthorization: ApiKey: api:79910a14-a82c-41f9-bb79-458247e6b31a\r\n\r\n{"username": "johnny", "type": "admin_user", "resource_uri": "/api/v1/table/10/"}'
reply: 'HTTP/1.0 401 UNAUTHORIZED\r\n'
header: Date: Fri, 15 Aug 2014 20:07:36 GMT
header: Server: WSGIServer/0.1 Python/2.7.5
header: X-Frame-Options: SAMEORIGIN
header: Content-Type: text/html; charset=utf-8
401 UNAUTHORIZED
但是当我在终端运行这个cURL
命令时:
curl -X PUT -v -H "Content-Type: application/json" -H "Authorization: ApiKey api:79910a14-a82c-41f9-bb79-458247e6b31a" --data '{"username": "johnny", "type": admin_user, "resource_uri": "/api/v1/table/1/"}' http://localhost:8000/api/v1/table/10/
它是可以正常工作的。(结果是204 NO CONTENT
,这是预期的结果)。不过,我找不到这两个调用和它们的数据之间有什么不同。有没有人能给我一些建议或者指点我哪里出错了?
1 个回答
5
"Authorization: ApiKey": '{0}:{1}'.format(username, key)
这个不是一个有效的头部。它应该像这样:
"Authorization": 'ApiKey {0}:{1}'.format(username, key)
在你的代码中,你发送的是这个(我认为一个好的库应该抛出一个异常,因为头部名称不能包含冒号):
Authorization: ApiKey: username:key
而不是这个:
Authorization: ApiKey username:key