【发布时间】:2011-12-06 17:24:09
【问题描述】:
有没有使用 Python 从 RESTful 服务获取 JSON 数据的标准方法?
我需要使用 kerberos 进行身份验证。
一些 sn-p 会有所帮助。
【问题讨论】:
-
我不是在寻找“基于 Python 的 REST 框架”。我想在python中使用一些java服务器提供的RESTful服务。还是谢谢。
有没有使用 Python 从 RESTful 服务获取 JSON 数据的标准方法?
我需要使用 kerberos 进行身份验证。
一些 sn-p 会有所帮助。
【问题讨论】:
首先,我认为为此推出自己的解决方案就是 urllib2 或 httplib2 。无论如何,如果您确实需要通用 REST 客户端,请查看此内容。
https://github.com/scastillo/siesta
但是我认为该库的功能集不适用于大多数 Web 服务,因为它们可能会使用 oauth 等 ..。此外,我不喜欢它是通过 httplib 编写的,与 httplib2 相比,如果您不必处理大量重定向等,它仍然应该为您工作..
【讨论】:
我会尝试使用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()
【讨论】:
requests 模块,只需执行以下操作:pip install requests。更多信息和文档here
除非我没有抓住重点,否则这样的事情应该可以工作:
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'))
【讨论】: