99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

Django drf Responses

2020-01-22 11:44 更新

Responses

與基本的HttpResponse對象不同, TemplateResponse 對象保留view提供的上下文的詳細信息以計算 response. Response的最終輸出直到它在稍后的響應(yīng)過程中被需要才會計算?!?nbsp;Django 文檔

REST framework 通過提供一個 Response 類來支持 HTTP content negotiation,該類允許你返回可以呈現(xiàn)為多種內(nèi)容類型的內(nèi)容,具體取決于客戶端的請求。

Response 類是 Django中 SimpleTemplateResponse 類的一個子類。Response 對象用Python基本數(shù)據(jù)類型初始化。 然后REST framework 使用標準的HTTP content negotiation 來確定如何呈現(xiàn)最終的響應(yīng)內(nèi)容。

你并不需要一定是用 Response 類,你可以從你的視圖返回常規(guī)的 HttpResponse 或者 StreamingHttpResponse 對象。使用Response類只提供了一個可以呈現(xiàn)多種格式的更好的界面來返回 content-negotiated 的 Web API 響應(yīng)。

除非由于某種原因你要對 REST framework 做大量的自定義,否則你應(yīng)該始終對返回對象的views使用 APIView 類或者 @api_view 函數(shù)。這樣做可以確保視圖在返回之前能夠執(zhí)行 content negotiation 并且為響應(yīng)選擇適當?shù)匿秩酒鳌?/p>

創(chuàng)建 responses

Response()

簽名: Response(data, status=None, template_name=None, headers=None, content_type=None)

與常規(guī)的 HttpResponse 對象不同,你不能使用渲染內(nèi)容來實例化一個 Response 對象,而是傳遞未渲染的數(shù)據(jù),包含任何Python基本數(shù)據(jù)類型。

Response 類使用的渲染器無法自行處理像 Django model 實例這樣的復(fù)雜數(shù)據(jù)類型,因此你需要在創(chuàng)建 Response 對象之前將數(shù)據(jù)序列化為基本數(shù)據(jù)類型。

你可以使用 REST framework的 Serializer 類來執(zhí)行此類數(shù)據(jù)的序列化,或者使用你自定義的來序列化。

參數(shù):

  • data: response的數(shù)列化數(shù)據(jù).
  • status: response的狀態(tài)碼。默認是200. 另行參閱 status codes.
  • template_name: HTMLRenderer 選擇要使用的模板名稱。
  • headers: A dictionary of HTTP headers to use in the response.
  • content_type: response的內(nèi)容類型。通常由渲染器自行設(shè)置,由content negotiation確定,但是在某些情況下,你需要明確指定內(nèi)容類型。

屬性

.data

Request 對象的未渲染內(nèi)容。

.status_code

HTTP 響應(yīng)的數(shù)字狀態(tài)嗎。

.content

response的呈現(xiàn)內(nèi)容。 .render() 方法必須先調(diào)用才能訪問 .content 。

.template_name

template_name 只有在使用 HTMLRenderer 或者其他自定義模板作為response的渲染器時才需要提供該屬性。

.accepted_renderer

將用于呈現(xiàn)response的render實例。

自動通過 APIView 或者 @api_view 在view返回response之前設(shè)置。

.accepted_media_type

由 content negotiation 階段選擇的媒體類型。

自動通過 APIView 或者 @api_view 在view返回response之前設(shè)置。

.renderer_context

一個將傳遞給渲染器的.render()方法的附加上下文信息字典。

自動通過 APIView 或者 @api_view 在view返回response之前設(shè)置。

標準的HttpResponse 屬性

Response 類擴展了 SimpleTemplateResponse,并且所有常用的屬性和方法都是提供的。比如你可以使用標準的方法設(shè)置response的header信息:

response = Response()

response['Cache-Control'] = 'no-cache'

.render()

Signature: .render()

和其他的 TemplateResponse 一樣,調(diào)用該方法將response的序列化數(shù)據(jù)呈現(xiàn)為最終的response內(nèi)容。 當 .render() 被調(diào)用時, response的內(nèi)容將被設(shè)置成在 accepted_renderer實例上調(diào)用 .render(data, accepted_media_type, renderer_context) 方法返回的結(jié)果。

你通常并不需要自己調(diào)用 .render() ,因為它是由Django的標準響應(yīng)周期來處理的。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號