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

requests.get(url).json() gives JSONDecodeError

我正在编写 api 以在另一个应用程序中获取一个应用程序的数据。我设置了视图以从 url 中获取数据,例如:

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 和 requests == 2.5.1。我已经检查了几乎所有内容,现在我开始得出结论,请求版本和 django 版本与以下回溯有关。我的虚拟环境中也安装了 simplejson==3.6.5,我认为这无关紧要。请帮忙。

你可以这样做

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 '})

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