Django中使用Json返回?cái)?shù)據(jù)的實(shí)現(xiàn)方法
在一個(gè)網(wǎng)站在,大量數(shù)據(jù)與前端交互,JSON是最好的傳遞數(shù)據(jù)方式了。
在Django中,使用JSON傳輸數(shù)據(jù),有兩種方式,一種是使用Python的JSON包,一種是使用Django的JsonResponse
方法一:使用Python的JSON包
from django.shortcuts import HttpResponse import json def testjson(request): data={ 'patient_name': '張三', 'age': '25', 'patient_id': '19000347', '診斷': '上呼吸道感染', } return HttpResponse(json.dumps(data))
我們暫且把data看成是從數(shù)據(jù)庫取出來的數(shù)據(jù),使用瀏覽器訪問一下testjson
咦,怎么是亂碼了?有中文的都是亂碼了?
不著急,這不是亂碼,這是中文在內(nèi)存中的二進(jìn)制表現(xiàn)形式而已,使用JSON的轉(zhuǎn)換工具可以看到中文的。
我們看一下Response Headers響應(yīng)頭,其中的Content-Type是text/html,我明明傳的是JSON啊,怎么會(huì)變成字符串類型了?這是因?yàn)槲覀儧]有告訴瀏覽器,我們要傳一個(gè)JSON數(shù)據(jù),那么,怎么告訴瀏覽器呢?
HttpResponse是繼承HttpResponseBase的,我們可以告訴瀏覽器,我要傳application/json數(shù)據(jù)。我們稍微改一下content的值,看看會(huì)變成什么?
def testjson(request): data={ 'patient_name': '張三', 'age': '25', 'patient_id': '19000347', '診斷': '上呼吸道感染', } return HttpResponse(json.dumps(data), content_type='application/json')
再訪問網(wǎng)頁:
這下好了,是傳輸JSON了,在Preview中可以正常顯示出來了。
方法二:使用JsonResponse進(jìn)行傳輸。
def testjson(request): data={ 'patient_name': '張三', 'age': '25', 'patient_id': '19000347', '診斷': '上呼吸道感染', } return JsonResponse(data)
訪問網(wǎng)頁:
嗯,一切正常。
看一下JsonResponse的源碼:
class JsonResponse(HttpResponse): """ An HTTP response class that consumes data to be serialized to JSON. :param data: Data to be dumped into json. By default only ``dict`` objects are allowed to be passed due to a security flaw before EcmaScript 5. See the ``safe`` parameter for more information. :param encoder: Should be a json encoder class. Defaults to ``django.core.serializers.json.DjangoJSONEncoder``. :param safe: Controls if only ``dict`` objects may be serialized. Defaults to ``True``. :param json_dumps_params: A dictionary of kwargs passed to json.dumps(). """ 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().__init__(content=data, **kwargs)
其內(nèi)部也是通過json.dumps來把數(shù)據(jù)轉(zhuǎn)換為JSON的,其還可以轉(zhuǎn)換為list類型。我們?cè)賮砀囊幌聇estjson
def testjson(request): listdata = ["張三", "25", "19000347", "上呼吸道感染"] return JsonResponse(listdata)
程序報(bào)錯(cuò)了
報(bào)錯(cuò)為:In order to allow non-dict objects to be serialized set the safe parameter to False,它的意思是轉(zhuǎn)換為一個(gè)非字典的類型時(shí),safe參數(shù)要設(shè)置為False,還記得上面JsonResponse的原碼嗎?其中就有
代碼修改為:
def testjson(request): listdata = ["張三", "25", "19000347", "上呼吸道感染"] return JsonResponse(listdata, safe=False)
嗯,這下正常了。
這有什么用呢?有時(shí)我們從數(shù)據(jù)庫取出來的數(shù)據(jù),很多是列表類型的,特別是用cx_Oracle包在Oracle數(shù)據(jù)庫取出來的數(shù)據(jù),其不支持直接字典的輸出,輸出就是一個(gè)list,這時(shí)我們使用JsonResponse(data, safe=False)就可以直接輸換為Json,發(fā)送到前端了。
到此這篇關(guān)于Django中使用Json返回?cái)?shù)據(jù)的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)Django Json返回?cái)?shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python全景系列之?dāng)?shù)據(jù)類型大盤點(diǎn)
這篇文章主要為大家介紹了Python全景系列之?dāng)?shù)據(jù)類型的盤點(diǎn)解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05python 實(shí)現(xiàn)將list轉(zhuǎn)成字符串,中間用空格隔開
今天小編就為大家分享一篇python 實(shí)現(xiàn)將list轉(zhuǎn)成字符串,中間用空格隔開,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-12-12python中g(shù)etaddrinfo()基本用法實(shí)例分析
這篇文章主要介紹了python中g(shù)etaddrinfo()基本用法,實(shí)例分析了Python中使用getaddrinfo方法進(jìn)行IP地址解析的基本技巧,需要的朋友可以參考下2015-06-06在cmd中運(yùn)行.py文件: python的操作步驟
今天小編就為大家分享一篇在cmd中運(yùn)行.py文件: python的操作步驟,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05