Django HttpResponse與JsonResponse

我們編寫一些接口函數(shù)的時候,經(jīng)常需要給調(diào)用者返回json格式的數(shù)據(jù),那么如何返回可直接解析的json格式的數(shù)據(jù)呢?

首先先來第一種方式:

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

通過訪問結(jié)果我們看到,在response的返回信息中,返回的Content-Type:是text/html,也就是字符串類型的返回,所以這段返回值并不是一個標(biāo)準(zhǔn)的json數(shù)據(jù),是一個長得像json數(shù)據(jù)的字符串,當(dāng)然可以通過工具直接轉(zhuǎn)換為json,不過既然是一個json的接口,那么我們拋出的數(shù)據(jù)自然是json格式的最好,那如何拋出標(biāo)準(zhǔn)json格式的數(shù)據(jù)呢?

稍稍修改一丟丟代碼,在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,他內(nèi)置的幫我們封裝了這個轉(zhuǎn)換的操作,也就是說如果我們的接口拋json數(shù)據(jù)的話那么將HttpResponse替換為JsonResponse就OK啦

看一下JsonResponse的源代碼,其實也很簡單了,強制的幫你做了一下轉(zhuǎn)換,同時也支持了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)

代碼改完后,訪問看輸出,結(jié)果發(fā)現(xiàn)報錯啦..為嘛?

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

是不是發(fā)現(xiàn)了什么?
嗯對,JsonResponse在拋出列表的時候需要將safe設(shè)置為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)

修改完成后,再次訪問


JsonResponse_list
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容