Backend - Django JsonResponse & HttpResponse

目录

一、关系

二、使用

(一)data 字典传值

1. JsonResponse

2. HttpResponse

3. 例子

(二)JsonResponse 有一个 safe 参数

(三)前端接收

1. 接收 JsonResponse 回传的值

2. 接收 HttpResponse 回传的值

3. 不分情况

(四)若报错:TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False

原因:

解决:

例子:


一、关系

        JsonResponse 是 HttpResponse 的一个子类。

        从1.7版本开始,Django使用内置JsonResponse类。

二、使用

(一)data 字典传值

1. JsonResponse

JsonResponse 的 data 参数是个字典。

# JsonResponse
from django.http import JsonResponse
return JsonResponse(mydict)

2. HttpResponse

HttpResponse 的 content 参数值必须是引号包裹的字符串。

比如,用 json.dumps 将 data 值转成JSON字串。

# HttpResponse
import json
return HttpResponse(json.dumps(mydict))

3. 例子

import json
from django.http import JsonResponse
data= {'name': '萝卜干'}

# 第一种
HttpResponse(json.dumps(data), content_type='application/json')  # 第一个参数位置,默认是content的参数值,第二个位置需要指定是什么参数的值,比如content_type=XXX

# 第二种(几乎等价于第一种)
JsonResponse(data)  # 默认的content_type='application/json'

(二)JsonResponse 有一个 safe 参数

safe:控制是否只有dict对象可以序列化,默认为 True。

若 safe 设置为True,但是 data 的数据类型不是 dict ,则抛出一个 TypeError 类型错误。

若想对非字典的数据(如列表)进行 dumps ,则 safe 设置为 False。

(三)前端接收

1. 接收 JsonResponse 回传的值

若使用JsonResponse传值,前台ajax收到的data不需要转JSON.parse(data),直接使用。

2. 接收 HttpResponse 回传的值

若使用HttpResponse传值,需要转JSON.parse(data)处理。

3. 不分情况

若是不考虑后台采用JsonResponse或者HttpResponse,则前台ajax处理时统一加属性:dataType:'json'。

(四)若报错:TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False

原因:

        JsonResponse中的参数要求字典,若非字典则报错。

解决:

        ① 传参数为字典。

        ② 设置参数safe=False。

例子:

return JsonResponse(result)
# 改为:
return JsonResponse(result, safe=False)

相关推荐

  1. Backend - Django JsonResponse & HttpResponse

    2023-12-05 16:18:06       21 阅读
  2. Backend - Python 序列化

    2023-12-05 16:18:06       33 阅读
  3. Backend - Django Middleware 中间件

    2023-12-05 16:18:06       24 阅读
  4. keras with pytorch backend : GPU版

    2023-12-05 16:18:06       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-05 16:18:06       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-05 16:18:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-05 16:18:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-05 16:18:06       18 阅读

热门阅读

  1. springmvc 重定向调节数据方法

    2023-12-05 16:18:06       38 阅读
  2. paddle 语谱图对比

    2023-12-05 16:18:06       34 阅读
  3. Flask 快速入门

    2023-12-05 16:18:06       42 阅读
  4. uniapp搭建内网映射测试https域名

    2023-12-05 16:18:06       46 阅读
  5. flask五小时快速入门资料记录

    2023-12-05 16:18:06       48 阅读
  6. Leetcode 2949. Count Beautiful Substrings II

    2023-12-05 16:18:06       41 阅读
  7. tortoisegit 报错:server refused to start a shell/command

    2023-12-05 16:18:06       41 阅读
  8. mybatis中<association> 和 <collection>

    2023-12-05 16:18:06       33 阅读
  9. 嵌入式硬件基础知识——1

    2023-12-05 16:18:06       35 阅读
  10. mySQL踩坑记录

    2023-12-05 16:18:06       43 阅读