2016-04-21 84 views
0

我试图从Django中的GET查询中获取API数据。我收到了响应HTML代码,其中也包含JSON。看起来Content-Type标题不起作用,这就是为什么我得到HTML代码作为响应。从Django中使用Python获取API的JSON数据

我测试做查询与邮差:

  • 当我没有Content-Type头可言,我得到了相同的HTML代码 像现在。
  • 当我将Content-Type标头设置为text/json时,它使用JSON数据响应 。

这是我在views.py的代码,我不希望这对网站的工作,所以我不回/渲染什么

def json_search(request): 
    query = request.GET.get('query') 
    final_url = urllib2.Request('http://APIwebsite.com', None, {'Content-Type':'text/json'}) 
    base64string = base64.encodestring('%s:%s' % ('username', 'password')).replace('\n', '') 
    final_url.add_header("Authorization", "Basic %s" % base64string) 
    json_obj = urllib2.urlopen(final_url) 
    decoded_data = json_obj.read() 
    print decoded_data 

由于响应我得到的HTML页面代码,CSS和JSON数据。我怎样才能得到只有JSON数据?

+0

我相信'Content-Type'应该是'application/json'而不是'text/json',并且json.loads调用应该在返回的响应中工作。另外,你使用的是什么Python版本? – Xk0nSid

+0

对我没有任何改变。我使用2.7.10。 – MMakela

回答

0

HTML页面有一个链接页面,其中只有JSON代码。所以,我查询了该页面,它的工作原理。尽管如此,我已经使用Javascript进行了相同的查询,并且它使用了正确的Content-Type标头。

0

使用try,

json.loads(request.body) 

JSON响应可以用这种方式来处理。

+0

我不确定我是否理解你,但是我发现属性主体不存在的错误。没有它,我得到错误“TypeError:预期的字符串或缓冲区”。 – MMakela

1

你可以写一个实用的方法,并在此之后传递参数中,例如

class JsonResponse(HttpResponse): 
    ''' 
     Handling content type for json no more to add content-type. 
    ''' 

    def __init__(self, content={}, status=None,content_type='application/json'): 
     super(JsonResponse, self).__init__(
      json.dumps(content), 
      status=status, content_type=content_type) 

您只需将数据传递给上述方法类似

response_json.update({"message": "success"}) 
return JsonResponse(response_json) 

这可能会解决你的问题。