码迷,mamicode.com
首页 > Web开发 > 详细

Django HttpResponse与JsonResponse

时间:2019-11-13 11:14:08      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:调用   std   **kwargs   访问   字符串类型   except   packages   enc   grant   

本文链接:https://blog.csdn.net/mr_hui_/article/details/86498509
 
我们编写一些接口函数的时候,经常需要给调用者返回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)

?
修改完成后,再次访问

Django HttpResponse与JsonResponse

标签:调用   std   **kwargs   访问   字符串类型   except   packages   enc   grant   

原文地址:https://www.cnblogs.com/Ph-one/p/11847098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!