RESR API (二)之Responses

Responses

与基本的HttpResponse对象不同,TemplateResponse对象保留 the details of the context that was provided by the view to compute the response。The final output of the response is not computed until it is needed, later in the response process.

Django文档

REST框架通过提供一个Response类来支持HTTP content negotiation,该类允许您根据客户端请求返回可以被渲染成多种内容类型的内容。

Response class是Django-SimpleTemplateResponse的子类。Response objects are initialised with data, which should consist of native Python primitives. 然后,REST框架使用标准HTTP内容协商来确定如何渲染最终响应内容。

您不需要使用Response类,如果需要,你也可以从视图中返回常规的HttpResponseStreamingHttpResponse对象。Using the Response class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats.

除非因为某些原因,您想大量自定义REST框架,否则您应该始终为返回Response 对象的视图使用APIView类或@api_view函数。这样做可以确保在从视图返回之前执行content negotiation并为响应选择适当的渲染器。


Creating responses

Response()

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

与常规HttpResponse对象不同,您不需要用 rendered content 实例化 Response对象。而是传递 unrendered data,这些数据可能由任何Python primitives 组成。

Response类使用的renderers 不能本地处理诸如Django-model实例等复杂的数据类型,因此您需要在创建Response对象之前将数据序列化为原始数据类型。

您可以使用REST框架的Serializer类来执行此数据序列化,或使用您自定义的serialization。

参数:

  • data:响应的序列化数据。
  • status:响应的状态码。默认为200.另请参见状态码
  • template_nameHTMLRenderer选择使用的模板名称。
  • headers:用于响应的HTTP标头字典。
  • content_type:响应的内容类型。通常,这将由content negotiation确定由renderer 自动设置,但在某些情况下,需要你明确指定内容类型。

Attributes

.data

The unrendered content of a Request object.

.status_code

HTTP响应的数字状态码。

.content

The rendered content of the response。.render()方法必须在.content被访问之前被调用。

.template_name

The template_name, if supplied. Only required if HTMLRenderer or some other custom template renderer is the accepted renderer for the response.

.accepted_renderer

用于渲染响应的渲染器实例。

从视图返回响应之前,由APIView@api_view自动设置。

.accepted_media_type

由the content negotiation stage 选择的媒体类型。

从视图返回响应之前,由APIView@api_view自动设置。

.renderer_context

将传递给渲染器.render()方法的附加上下文信息的字典。

从视图返回响应之前,由APIView@api_view自动设置。


标准的HttpResponse属性

Response类了扩展SimpleTemplateResponse,所有常见的属性和方法都可用在响应中。例如,您可以以标准方式在响应中设置头文件:

1
2
response  =  Response()
response[ 'Cache-Control' =  'no-cache'

.render()

签名: .render()

与其他任何TemplateResponse一样,该方法可把响应的序列化数据渲染为最终的响应内容。When .render() is called, the response content will be set to the result of calling the .render(data, accepted_media_type, renderer_context) method on the accepted_renderer instance.

通常我们不需要调用.render(),as it's handled by Django's standard response cycle.

猜你喜欢

转载自www.cnblogs.com/yucaikang/p/8983931.html