您的位置:首頁技術文章
文章詳情頁

對python中各個response的使用說明

瀏覽:9日期:2022-07-31 18:12:23

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?冉ㄊ?堇嘈停?RF會使用render渲染器處理data

以上這篇對python中各個response的使用說明就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
国产综合久久一区二区三区