Python django中我们经常用的response有django中的 JsonResponse, HttpResponse,还有DRF中的Response

在使用的时候,经常会不知道如何什么时候选择用哪个response

下面简单记录下这三个response的区别

1、HttpResponse

  它的返回格式为:HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)

  1)它可以返回普通文本信息

    HttpResponse("哈哈哈哈")

python中各个response使用

 

 

 2)它可以像文本一样追加内容:

    res = HttpResponse("哈哈哈哈")

    res.write("<p>恩,我们是一个测试段落</p>")

python中各个response使用

 

 

  3、它还可以返回图片,音频,视频等二进制文件信息

    img = open(filepath,"rb")

    data = img.read()

    return HttpResponse(data, content_type="image/png")

python中各个response使用

 

 

2、JsonResponse

  它继承自HttpResponse,它主要用于返回json格式的数据

  JsonResponse(jsonData,content_type="application/json")

python中各个response使用

 

 

 3、RestFramework框架封装的Response

  它的返回格式为:

    Response(data, status=None,template_name=None, header=None, content_type=None)

  data:为python內建数据类型,DRF会使用render渲染器处理data

 

摘选

原作者地址:https://www.cnblogs.com/fiona-zhong/p/9958414.html

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
猜你喜欢
  • 2021-09-05
  • 2022-12-23
  • 2021-10-08
  • 2022-12-23
  • 2022-12-23
  • 2022-01-10
  • 2022-02-09
相关资源
相似解决方案