python ajax获取json数据_如何从使用Python的RESTful服务获取JSON数据?

这样的事情应该工作,除非我错过了重点:

import json import urllib2 json.load(urllib2.urlopen("url"))

我会给这个请求库一个尝试。 从本质上来说,使用标准库模块(例如urllib2,httplib2等)的包装器要容易得多。 例如,要从需要基本身份validation的url中获取json数据,如下所示:

import requests response = requests.get('http://thedataishere.com', auth=('user', 'password')) data = response.json()

对于kerberos身份validation, 请求项目具有reqests-kerberos库,它提供了一个kerberos身份validation类,您可以使用该请求 :

import requests from requests_kerberos import HTTPKerberosAuth response = requests.get('http://thedataishere.com', auth=HTTPKerberosAuth()) data = response.json()

您基本上需要对服务进行HTTP请求,然后parsing响应的主体。 我喜欢使用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'))

那么首先我想,推出你自己的解决scheme,这一切你需要的是urllib2或httplib2。 无论如何,如果你需要一个通用的REST客户端检查了这一点。

不过,我认为图书馆的function集不适用于大多数Web服务,因为他们可能会使用oauth等。 另外我不喜欢这样的事实,它是写在httplib这是一个痛苦的httplib2相比,仍然应该为你工作,如果你不必处理很多redirect等。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值