一、请求对象(Request)
REST framework 传⼊视图的request对象不再是Django默认的HttpRequest对象,⽽是REST framework提供的扩展了HttpRequest类的Request类的对象。
REST framework 提供了Parser解析器,在接收到请求后会⾃动根据Content-Type指明的请求数据类型(如JSON、表单等)将请求数据进⾏parse解析,解析为类字典对象保存到Request对象中。
Request对象的数据是⾃动根据前端发送数据的格式进⾏解析之后的结果。
⽆论前端发送的哪种格式的数据,我们都可以以统⼀的⽅式读取数据。
1、request.data:返回解析之后的请求体数据。类似于Django中标准的request.POST和request.FILES属性,但提供如下特性:
- 包含了解析之后的⽂件和⾮⽂件数据
- 包含了对POST、PUT、PATCH请求⽅式解析后的数据
- 利⽤了REST framework的parsers解析器,不仅⽀持表单类型数据,也⽀持JSON数据
2、request.query_params:查询字符串参数
request.query_params与Django标准的request.GET相同,只是更换了更正确的名称⽽已。
二、响应对象(Response)
rest_framework.response.Response
REST framework提供了⼀个响应类Response,使⽤该类构造响应对象时,响应的具体数据内容会被转换(render渲染)成符合前端需求的类型。
构造方式:
Response(data, status=None, template_name=None, headers=None, content_type=None)
参数说明:
data: 为响应准备的序列化数据;
status: 状态码,默认200;
template_name: 模板名称,如果使⽤HTMLRenderer 时需指明;
headers: ⽤于存放响应头信息的字典;
content_type: 响应数据的Content-Type,通常此参数⽆需传递,REST framework会根据前端所需类型数据来设置该参数。
三、状态码
为了⽅便设置状态码,REST framewrok在rest_framework.status模块中提供了常⽤状态码常量。
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)客户端错误 - 4xx
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