有没有标准的方法可以使用Python从RESTful服务获取JSON数据?
我需要使用kerberos进行身份验证。
一些代码片段会很有帮助。
我建议尝试使用requests库。它本质上只是标准库模块(即urllib2、httplib2等)的一个更简单易用的封装。例如,要从需要基本身份验证的URL获取JSON数据,代码如下:
import requests
response = requests.get('http://thedataishere.com',
auth=('user', 'password'))
data = response.json()
使用Kerberos认证时,requests项目提供了reqests-kerberos库,该库提供了一个Kerberos认证类,您可以与requests一起使用:
import requests
from requests_kerberos import HTTPKerberosAuth
response = requests.get('http://thedataishere.com',
auth=HTTPKerberosAuth())
data = response.json()
如果我没理解错,像这样应该可以工作:
import json
import urllib2
json.load(urllib2.urlopen("url"))
你需要向服务发送HTTP请求,然后解析响应体。我喜欢使用httplib2:
import httplib2 as http
import json
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
}
uri = 'http://yourservice.com'
path = '/path/to/resource/'
target = urlparse(uri+path)
method = 'GET'
body = ''
h = http.Http()
# If you need authentication some example:
if auth:
h.add_credentials(auth.user, auth.password)
response, content = h.request(
target.geturl(),
method,
body,
headers)
# assume that content is a json reply
# parse content with the json module
data = json.loads(content)
如果您想使用Python 3,可以使用以下内容:
import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
result = json.loads(response.readall().decode('utf-8'))
首先,我认为如果你想要实现这个功能,只需要使用urllib2或httplib2就可以了。无论如何,如果你确实需要一个通用的REST客户端,请查看此内容。
然而,我认为该库的功能集对于大多数Web服务来说不适用,因为它们可能会使用oauth等。此外,我不喜欢它是在httplib上编写的,这比httplib2更麻烦,但如果您不必处理大量重定向等问题,则应该可以使用。