DRF自带的Request和Response对象(DRF基类APIView)

# 转载请留言联系

1.Request对象

DRF传入视图的request对象,不再是Django默认的HttpRequest对象,而是扩展了HttpRequest类的Request类的对象。

REST framework 提供了Parser解析器,在接收到请求后会自动根据Content-Type指明的请求数据类型(如JSON、表单等)将请求数据进行parse解析,解析为字典对象保存到Request对象中。

Request对象的数据是自动根据前端发送数据的格式进行解析之后的结果。无论前端发送的哪种格式的数据,我们都可以以统一的方式读取数据。

  • Request的常用属性

1) .data

  • 包含了解析之后的文件和非文件数据
  • 包含了对POST、PUT、PATCH请求方式解析后的数据
  • 利用了REST framework的parsers解析器,不仅支持表单类型数据,也支持JSON数据

简单来说,无论前端发过来的是xml还是json,请求方式无论是POST还是PUT,都可以直接用request.data直接取一个字典出来。

示例:

# 要继承APIView(或其子类)才能取得DRF的Request和Response
class DepartmentListAPIView(APIView):
    def post(self,request):
        """
        :param request:这个request是DRF传入视图的request对象,不再是Django默认的HttpRequest对象。
        :return:
        """
        data = request.data
        print(type(data))    # 输出结果:<class 'dict'>
        name = data.get("name")
        age = data.get("age")
        print(name)
        print(age)
        return HttpResponse("for test")

 

2).query_params

与Django原来的HttpRequest的GET方法一样,只不过换了个名字...

示例:

class DepartmentListAPIView2(APIView):
    def get(self,request):
        a = request.query_params  # 与HttpRequest对象的GET方法相同
        print(a.get("id"))
        return HttpResponse("hello")

 

2.Response对象

REST framework提供了一个响应类Response,使用该类构造响应对象时,响应的具体数据内容会被转换(render渲染)成符合前端需求的类型。

REST framework提供了Renderer 渲染器,用来根据请求头中的Accept(接收数据类型声明)来自动转换响应数据到对应格式。如果前端请求中未进行Accept声明,则会采用默认方式处理响应数据,我们可以通过配置来修改默认响应格式。

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (                           # 默认响应渲染类
        'rest_framework.renderers.JSONRenderer',              # json渲染器
        'rest_framework.renderers.BrowsableAPIRenderer',      # 浏览API渲染器
    )
}
  • 构造方式:

Response(data, status=None, headers=None)

示例:

class DepartmentListAPIView2(APIView):
    def get(self,request):
        data=[1,2,3]
        response = Response(data=data,status=status.HTTP_200_OK,headers={"aaa":"111","bbb":"222"})  # status可以直接写status=200
        return response

 

状态码附录:

1)信息告知-1xx

HTTP_100_CONTINUE
HTTP_101_SWITCHING_PROTOCOLS

2)成功-2xx

HTTP_200_OK
HTTP_201_CREATED
HTTP_202_ACCEPTED
HTTP_203_NON_AUTHORITATIVE_INFORMATION
HTTP_204_NO_CONTENT
HTTP_205_RESET_CONTENT
HTTP_206_PARTIAL_CONTENT
HTTP_207_MULTI_STATUS

3)重定向-3xx

HTTP_300_MULTIPLE_CHOICES
HTTP_301_MOVED_PERMANENTLY
HTTP_302_FOUND
HTTP_303_SEE_OTHER
HTTP_304_NOT_MODIFIED
HTTP_305_USE_PROXY
HTTP_306_RESERVED
HTTP_307_TEMPORARY_REDIRECT

4)客户端错误

HTTP_400_BAD_REQUEST
HTTP_401_UNAUTHORIZED
HTTP_402_PAYMENT_REQUIRED
HTTP_403_FORBIDDEN
HTTP_404_NOT_FOUND
HTTP_405_METHOD_NOT_ALLOWED
HTTP_406_NOT_ACCEPTABLE
HTTP_407_PROXY_AUTHENTICATION_REQUIRED
HTTP_408_REQUEST_TIMEOUT
HTTP_409_CONFLICT
HTTP_410_GONE
HTTP_411_LENGTH_REQUIRED
HTTP_412_PRECONDITION_FAILED
HTTP_413_REQUEST_ENTITY_TOO_LARGE
HTTP_414_REQUEST_URI_TOO_LONG
HTTP_415_UNSUPPORTED_MEDIA_TYPE
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
HTTP_417_EXPECTATION_FAILED
HTTP_422_UNPROCESSABLE_ENTITY
HTTP_423_LOCKED
HTTP_424_FAILED_DEPENDENCY
HTTP_428_PRECONDITION_REQUIRED
HTTP_429_TOO_MANY_REQUESTS
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS

5)服务器错误-5xx

HTTP_500_INTERNAL_SERVER_ERROR
HTTP_501_NOT_IMPLEMENTED
HTTP_502_BAD_GATEWAY
HTTP_503_SERVICE_UNAVAILABLE
HTTP_504_GATEWAY_TIMEOUT
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
HTTP_507_INSUFFICIENT_STORAGE
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
posted @ 2018-11-10 16:51  苦瓜爆炒牛肉  阅读(1685)  评论(0编辑  收藏  举报