在Django中使用Python从API获取JSON数据

时间:2016-04-21 09:05:07

标签: python json django django-views

我试图在Django中使用GET查询从API获取数据。我得到了响应HTML代码,其中也包含JSON。似乎Content-Type标题不起作用,这就是我将HTML代码作为响应的原因。

我测试过使用Postman进行查询:

  • 当我根本没有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

作为响应,我使用CSS和JSON数据获取HTML页面代码。我怎么只能获得JSON数据?

3 个答案:

答案 0 :(得分: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)

这可能会解决您的问题。

答案 1 :(得分:0)

尝试使用,

json.loads(request.body)

可以使用这种方式处理Json响应。

答案 2 :(得分:0)

HTML页面有一个指向页面的链接,其中只有JSON代码。所以,我对该页面进行了查询,并且它有效。虽然,我使用Javascript进行了相同的查询,但它使用了正确的Content-Type标题。