Django HttpResponse与JsonResponse

我们编写一些接口函数的时候,经常需要给调用者返回json格式的数据,那么如何返回可直接解析的json格式的数据呢?

首先先来第一种方式:

from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
import json

# Create your views here.

def index(request):
    data={
        'name':'zhangsan',
        'age':18,
    }
    return HttpResponse(json.dumps(data))

访问一下


Django HttpResponse与JsonResponse_第1张图片
text/html

通过访问结果我们看到,在response的返回信息中,返回的Content-Type:是text/html,也就是字符串类型的返回,所以这段返回值并不是一个标准的json数据,是一个长得像json数据的字符串,当然可以通过工具直接转换为json,不过既然是一个json的接口,那么我们抛出的数据自然是json格式的最好,那如何抛出标准json格式的数据呢?

稍稍修改一丢丢代码,在HttpResponse中添加content_type类型为json的属性

from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
import json

# Create your views here.

def index(request):
    data={
        'name':'zhangsan',
        'age':18,
    }
    return HttpResponse(json.dumps(data),content_type="application/json")
Django HttpResponse与JsonResponse_第2张图片
application/json

诺,这下返回的类型正常了

不过这里还是要提另外一个模块JsonResponse,他内置的帮我们封装了这个转换的操作,也就是说如果我们的接口抛json数据的话那么将HttpResponse替换为JsonResponse就OK啦

看一下JsonResponse的源代码,其实也很简单了,强制的帮你做了一下转换,同时也支持了list的输出

class JsonResponse(HttpResponse):
    def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super(JsonResponse, self).__init__(content=data, **kwargs)

下边我们来尝试使用JsonResponse输出一下dict和list

首先是dict

from django.shortcuts import render
from django.http import HttpResponse,JsonResponse

# Create your views here.

def index(request):
    data={
        'name':'zhangsan',
        'age':18,
    }
    return JsonResponse(data)
Django HttpResponse与JsonResponse_第3张图片
JsonResponse_dict

下面看下list

from django.shortcuts import render
from django.http import HttpResponse,JsonResponse

# Create your views here.

def index(request):

    listdata=[1,2,3,4,5]
    return JsonResponse(listdata)

代码改完后,访问看输出,结果发现报错啦..为嘛?

TypeError at /mytest/hello/
In order to allow non-dict objects to be serialized set the safe parameter to False.
Request Method: GET
Request URL:    http://10.89.0.5:8000/mytest/hello/
Django Version: 1.11.13
Exception Type: TypeError
Exception Value:    
In order to allow non-dict objects to be serialized set the safe parameter to False.
Exception Location: /data/python36env/lib/python3.6/site-packages/django/http/response.py in __init__, line 524
Python Executable:  /data/python36env/bin/python
Python Version: 3.6.4
Python Path:    
['/vagrant/reboot_dj',
 '/data/python36env/lib/python36.zip',
 '/data/python36env/lib/python3.6',
 '/data/python36env/lib/python3.6/lib-dynload',
 '/usr/local/python36/lib/python3.6',
 '/data/python36env/lib/python3.6/site-packages']
Server time:    Mon, 4 Jun 2018 11:53:32 +0000

看这行的提示:In order to allow non-dict objects to be serialized set the safe parameter to False.
然后再看看JsonResponse的源代码

 if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )

是不是发现了什么?
嗯对,JsonResponse在抛出列表的时候需要将safe设置为False safe=False

from django.shortcuts import render
from django.http import HttpResponse,JsonResponse

# Create your views here.

def index(request):

    listdata=[1,2,3,4,5]
    return JsonResponse(listdata,safe=False)

修改完成后,再次访问


Django HttpResponse与JsonResponse_第4张图片
JsonResponse_list

你可能感兴趣的:(Django HttpResponse与JsonResponse)