有没有使用Python从RESTful服务获取JSON数据的标准方法?
我需要使用kerberos进行身份验证。
一些片段会有所帮助。
答案 0 :(得分:115)
我会试试requests库。基本上只是一个更容易使用的标准库模块(即urllib2,httplib2等)的包装器,你可以使用相同的东西。例如,从需要基本身份验证的URL获取json数据将如下所示:
import requests
response = requests.get('http://thedataishere.com',
auth=('user', 'password'))
data = response.json()
对于kerberos身份验证,requests project具有reqests-kerberos库,该库提供可与requests一起使用的kerberos身份验证类:
import requests
from requests_kerberos import HTTPKerberosAuth
response = requests.get('http://thedataishere.com',
auth=HTTPKerberosAuth())
data = response.json()
答案 1 :(得分:77)
除非我忽视这一点,否则这样的事情应该有效:
import json
import urllib2
json.load(urllib2.urlopen("url"))
答案 2 :(得分: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)
答案 3 :(得分:8)
如果您希望使用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'))
答案 4 :(得分:3)
首先,我认为推出自己的解决方案就是你需要的所有urllib2或httplib2。无论如何,如果您确实需要通用REST客户端,请检查这一点。
https://github.com/scastillo/siesta
但是我认为库的功能集对大多数Web服务都不起作用,因为它们可能会使用oauth等。另外我不喜欢它写在httplib上这是一个很痛苦的事实,与httplib2相比,如果你不需要处理大量的重定向等,它仍然适用于你。