【django】HttpResponse对象
生活随笔
收集整理的這篇文章主要介紹了
【django】HttpResponse对象
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
視圖在接收請求并處理后,必須返回HttpResponse對象或?對象。HttpRequest對象由Django創(chuàng)建,HttpResponse對象由開發(fā)?員創(chuàng)建。
一、HttpResponse
可以使?django.http.HttpResponse來構(gòu)造響應(yīng)對象。
HttpResponse(content=響應(yīng)體, content_type=響應(yīng)體數(shù)據(jù)類型, status=狀態(tài)碼)也可通過HttpResponse對象屬性來設(shè)置響應(yīng)體、響應(yīng)體數(shù)據(jù)類型、狀態(tài)碼:
content:表示返回的內(nèi)容。
status_code:返回的HTTP響應(yīng)狀態(tài)碼。 響應(yīng)頭可以直接將HttpResponse對象當(dāng)做字典進?響應(yīng)頭鍵值對的設(shè)置:
示例:
二、HttpResponse?類
Django提供了?系列HttpResponse的?類,可以快速設(shè)置狀態(tài)碼
HttpResponseRedirect 302 HttpResponsePermanentRedirect 301 HttpResponseNotModified 304 HttpResponseBadRequest 400 HttpResponseNotFound 404 HttpResponseForbidden 403 HttpResponseNotAllowed 405 HttpResponseGone 410 HttpResponseServerError 500三、JsonResponse
若要返回json數(shù)據(jù),可以使?JsonResponse來構(gòu)造響應(yīng)對象,作?:
1、幫助我們將數(shù)據(jù)轉(zhuǎn)換為json字符串
2、設(shè)置響應(yīng)頭Content-Type為application/json
四、redirect重定向
from django.shortcuts import redirect def response(request): return redirect('/otherView/')總結(jié)
以上是生活随笔為你收集整理的【django】HttpResponse对象的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【django】路由命名和路由反向解析
- 下一篇: 【django】HttpRequest对