zoukankan      html  css  js  c++  java
  • Django中的HttpResponse和JsonResponse

    Django中的HttpResponse和JsonResponse

    我们在编写一些借口函数的时候,经常需要给调用者返回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:是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了;

    那么Django提供了更方便的方法那就是JsonResponse,它内置帮我们封装了这个转换的操作,也就是说我们的接口抛json数据的话那么将HttpResponse替换为JsonResponse就OK了

    1. 首先先传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)
    

    成功收到json数据;

    1. 接着再试试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)
    

    此时查看输出,却报错了``In order to allow non-dict objects to be serialized set the safe parameter to False.`

    所以我们如果需要将非dict类型的数据进行JsonResponse传值,需要将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)
    

    此时成功接收到数据。

    1. 如果我们需要使用JsonResponse传中文
    def func(request):
        data={'姓名':'释明空'}
        return JsonResponse(data,json_dumps_params={'ensure_ascii':False})
    
    

    此时需要添加'json_dumps_params={'ensure_ascii':False}',因为json序列化中文用的是ascii编码,所以传到前台的中文是ascii字符码,需要这一步转化为中文。

  • 相关阅读:
    RatProxy
    Jacob
    系统二级运维之业务单据错误处理
    材料的构成 —— 塑料
    作文 —— 诙谐、幽默、调侃、批判
    作文 —— 诙谐、幽默、调侃、批判
    (中英)作文 —— 标题与小标题
    公司的组成
    公司的组成
    数据结构的时间复杂度与空间复杂度、及相关证明
  • 原文地址:https://www.cnblogs.com/zhoajiahao/p/11466560.html
Copyright © 2011-2022 走看看