如何使用Python从RESTful服务获取JSON数据?
有没有什么标准的方法可以用Python从RESTful服务获取JSON数据?
我需要用kerberos进行身份验证。
如果能给点代码示例就好了。
5 个回答
27
你基本上需要向服务发送一个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)
127
我建议你试试requests这个库。简单来说,它是一个更容易使用的工具,帮你简化了标准库模块(比如urllib2、httplib2等)在做同样事情时的复杂性。比如,如果你想从一个需要基本认证的链接获取json数据,代码看起来会像这样:
import requests
response = requests.get('http://thedataishere.com',
auth=('user', 'password'))
data = response.json()
如果你需要使用kerberos认证,requests项目提供了一个叫requests-kerberos的库,它里面有一个kerberos认证的类,你可以和requests一起使用:
import requests
from requests_kerberos import HTTPKerberosAuth
response = requests.get('http://thedataishere.com',
auth=HTTPKerberosAuth())
data = response.json()
77
像这样的代码应该可以正常工作,除非我理解错了什么:
import json
import urllib2
json.load(urllib2.urlopen("url"))