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

​

访问一下

 

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")

​

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)

​

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)

​

修改完成后,再次访问

 

  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值