requests.get(url).json()给出了JSONDecodeError

时间:2015-02-03 11:07:39

标签: python django django-rest-framework

我正在编写一个API来获取另一个应用程序中的应用程序数据。我设置了我的视图以从网址获取数据:

import requests
user = 'hello'
pwd = 'python'
class SomeView(APIView):
    def get(self, request):
        if request.user.is_authenticated():
            r = requests.get('http://localhost:8000/foo/bar/', 
                auth=HTTPBasicAuth(user, pwd))
            return HttpResponse(r.json())
        else:
            return HttpResponse(json.dumps({'success':'false', 'message':'login required '}))

这给我一个错误:

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/requests/models.py", line 799, in json
return json.loads(self.text, **kwargs)
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/simplejson/__init__.py", line 505, in loads
return _default_decoder.decode(s)
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/simplejson/decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/simplejson/scanner.py", line 127, in scan_once
return _scan_once(string, idx)
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/simplejson/scanner.py", line 118, in _scan_once
raise JSONDecodeError(errmsg, string, idx)
JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我在我的虚拟环境中安装了django == 1.4.5并请求== 2.5.1。我已经检查了几乎所有内容,现在我开始得出结论,请求版本和django版本与以下回溯有关。我也在我的虚拟环境中安装了simplejson == 3.6.5,我认为没有相关性。请帮忙。

2 个答案:

答案 0 :(得分:0)

你可以做这样的事情

import requests
from rest_framework.response import Response
...

if request.user.is_authenticated():
    r = requests.get('http://localhost:8000/foo/bar/', 
                     auth=HTTPBasicAuth(user, pwd))
    return Response(r.json())
return Response({'success':'false', 'message':'login required '})

答案 1 :(得分:0)

我在验证方面遇到了一些问题。修复了身份验证并修复了错误。感谢大家的帮助!!