我正在通过他们的HTTP API向OrientDB发出GET请求,这似乎与上述3个模块返回3个不同的结果。
uri = 'http://localhost:2480/query/Test1/sql/Select from Person'
# Requests
import requests
r = requests.get(uri, auth = ('root', 'root'))
print r.status_code #200
r.json() # Returns the results from the query, all good
# httplib2
import httplib2
h = httplib2.Http()
h.add_credentials('root', 'root')
r = h.request(uri = uri, method = 'GET')
print r
#this returns status 200, but the response itself says 401 unauthorized.
#({'content-location': 'http://localhost:2480/query/Test1/sql/Select from Person',
# 'status': '200'},
# 'from 401 Unauthorized\r\nCache-Control: no-cache, no-store, max-age=0, must-revalidate\r\nPragma: no-cache\r\nDate: Fri Jun 26 10:45:26 IDT 2015\r\nContent-Type: text/plain; charset=utf-8\r\nServer: OrientDB Server v.2.0.8 (build UNKNOWN@r; 2015-04-22 20:47:49+0000)\r\nConnection: Keep-Alive\r\nWWW-Authenticate: Basic realm="OrientDB db-Test1"\r\nSet-Cookie: OSESSIONID=-; Path=/; HttpOnly\r\nContent-Length: 17\r\n\r\n401 Unauthorized.')
# This however returns the correct result, meaning we are authorized!
h.request(uri = 'http://localhost:2480/document/Test1/12:0',
method = 'GET')
#urllib3
import urllib3
http = urllib3.PoolManager()
headers = urllib3.util.make_headers(basic_auth = 'root:root')
r = http.request('GET', uri, headers = headers)
print r.data
# This returns some weird response, definitely not what I got with requests module.
# This isn't the expected from my query either
# 'from 200 OK\r\nCache-Control: no-cache, no-store, max-age=0, must-revalidate\r\nPragma: no-cache\r\nDate: Fri Jun 26 10:51:23 IDT 2015\r\nContent-Type: application/json; charset=utf-8\r\nServer: OrientDB Server v.2.0.8 (build UNKNOWN@r; 2015-04-22 20:47:49+0000)\r\nConnection: Keep-Alive\r\nSet-Cookie: OSESSIONID=OS1435305083836-80491934664057070; Path=/; HttpOnly\r\nContent-Length: 54\r\n\r\n{"result":[{"@type":"d","@rid":"#-2:0","@version":0}]}'
# This however returns actual results
http.request('GET', 'http://localhost:2480/document/Test1/12:0', headers = headers)
我真的不知道这里发生了什么。从浏览器运行sql查询请求会返回预期的结果,与请求相同。
我也尝试过使用标题,但没有帮助......
我无法判断
是否有问题那么,为什么所有三个模块都返回三个不同的结果,我如何制作httplib& urllib返回正确的结果?
谢谢!
修改
阅读this后(感谢dano),我通过手动为请求添加身份验证标头,通过httplib2传递了401响应。
然而,httplib仍然会返回urllib所做的完全相同的响应 - 一个奇怪的响应,id = -2,这意味着什么。请求仍然返回实际结果。
为什么Requests是唯一能够获得实际结果的人?!
答案 0 :(得分:1)
我认为您httplib2
所看到的是actually by design;当您提供凭据时,httplib2
不会在第一次请求时将其传递给服务器。如果服务器返回401状态,它将再次使用包含的凭据进行尝试。由于看起来你已经获得200状态(尽管有消息说它是401),但它可能不会发送信用证。您可以尝试通过手动将凭据添加到请求的标头来解决此问题:
import base64
import httplib2
h = httplib2.Http()
auth = base64.encodestring( 'root' + ':' + 'root' )
r = h.request(uri, method='GET',
headers = {'Authorization' : 'Basic ' + auth}
)
我不是100%肯定,但我的猜测是urllib3
问题是由于你的uri中的空白。看看它是否适用于http.request_encode_url
而不是http.request
。