Django中構造響應對象的方式


1 HttpResponse

可以使用django.http.HttpResponse來構造響應對象。

HttpResponse(content=響應體, content_type=響應體數據類型, status=狀態碼) 

也可通過HttpResponse對象屬性來設置響應體、響應體數據類型、狀態碼:

  • content:表示返回的內容。
  • status_code:返回的HTTP響應狀態碼。
  • content_type:指定返回數據的的MIME類型。

響應頭可以直接將HttpResponse對象當做字典進行響應頭鍵值對的設置:

response = HttpResponse() response['object'] = 'Python' # 自定義響應頭object, 值為Python 

示例:

from django.http import HttpResponse def demo_view(request): return HttpResponse('object python', status=400) 或者 response = HttpResponse('object python') response.status_code = 400 response['object'] = 'Python' return response 

2 HttpResponse子類

Django提供了一系列HttpResponse的子類,可以快速設置狀態碼

  • HttpResponseRedirect 301
  • HttpResponsePermanentRedirect 302
  • HttpResponseNotModified 304
  • HttpResponseBadRequest 400
  • HttpResponseNotFound 404
  • HttpResponseForbidden 403
  • HttpResponseNotAllowed 405
  • HttpResponseGone 410
  • HttpResponseServerError 500

3 JsonResponse

若要返回json數據,可以使用JsonResponse來構造響應對象,作用:

  • 幫助我們將數據轉換為json字符串
  • 設置響應頭Content-Type為 application/json
from django.http import JsonResponse def demo_view(request): return JsonResponse({'city': 'beijing', 'subject': 'python'})

   第二個參數為 safe=True , 如果safe=False那可以傳入任何能被轉換為JSON格式的對象,比如list, tuple, set。

默認的safe 參數是 True. 如果你傳入的data數據類型不是字典類型,那么它就會拋出 TypeError的異常。

4 redirect重定向

from django.shortcuts import redirect def demo_view(request): return redirect('/index.html')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM