我正在尝试在 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
,这是预期的)。但是,我找不到这两个调用及其数据之间的任何差异。有没有人对我在这里出错的地方有任何想法或指示?
最佳答案
"Authorization: ApiKey": '{0}:{1}'.format(username, key)
这不是一个有效的标题。它应该看起来像这样:
"Authorization": 'ApiKey {0}:{1}'.format(username, key)
用你的代码发送这个(在我看来,一个体面的库应该引发异常,因为标题名称不能包含冒号):
Authorization: ApiKey: username:key
而不是这个:
Authorization: ApiKey username:key
关于Python - 使用 httplib 来 PUT JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25334017/