drf(请求和响应)

一 请求

源码分析

from rest_framework.request import Request


class Request:
    def __init__(self, request, parsers=None, authenticators=None,
                 negotiator=None, parser_context=None):
        # 二次封装request,将原生request作为drf中request对象的 _request 属性
        self._request = request

    def __getattr__(self, item):
        return getattr(self._request, item)
    
    # 请求对象: request.data  前端以三种编码方式传入的数据,都可以取出来
    # 请求对象: request.query_params与Django标准的request.GET相同,只是更换了更正确的名称而已。

二. 响应

1.参数介绍

Response类

from  rest_framwork.response import Response
def __init__(self, data=None, status=None,
             template_name=None, headers=None,
             exception=False, content_type=None):

# data:你要返回的数据,字典
# status:返回的状态码,默认是200
from rest_framework import status
# 所有的状态码都在这路径下,定义成了常量

# template_name 渲染的模版名字(自定制模版)
# headers:响应头,可以往响应头放东西,就是一个字典
# content_type: 响应的编码格式,application/json和text/html

2. 控制返回响应格式浏览器响应成浏览器的格式

postman响应成json格式,浏览器响应好看的页面. 这都是通过配置实现的(默认配置)

# 配置的加载执行顺序: 先从自己类中找 -> 项目的setting中找 -> 默认配置文件中找


# 局部使用: 对某个视图类有效, 在视图类中写如下:

from rest_framework.renderers import JSONRenderer
class MyName(APIView):
  renderer_classes = [JSONRenderer] # 局部配置视图类,浏览器不渲染

  def get(self, request):
    return Response({'name': 'lq'}, status=200, headers={'token': 'xxx'}, content_type='application/json')

# 全局使用:全局的视图类,所有请求,都有效. 在setting.py中加入如下:
    REST_FRAMEWORK = {
        'DEFAULT_RENDERER_CLASSES': (  # 默认响应渲染类
            'rest_framework.renderers.JSONRenderer',          # json渲染器
            'rest_framework.renderers.BrowsableAPIRenderer',  # 浏览API渲染器
        )
    }

3. 状态码

为了方便设置状态码,REST framewrok在rest_framework.status模块中提供了常用状态码常量。

导入: from rest_framework import status

提示: 默认响应状态码200

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

 三 封装Response对象

utils.py

from rest_framework.response import Response


class CommonResponse(Response):
    def __init__(self, code=1000, messages='ok', results=None,
                 status=None, template_name=None, headers=None,
                 exception=False, content_type=None,
                 **kwargs):
        data = {
            'code': code,
            'messages': messages,
        }
        data.update(kwargs)
        if results:
            data['results'] = results
        super().__init__(data=data, status=status,
                         template_name=template_name, headers=headers,
                         exception=exception, content_type=content_type)

 

posted @ 2023-09-25 21:17  coder雪山  阅读(37)  评论(0编辑  收藏  举报