以前我们通过django开发项目时,视图中的request是 django.core.handlers.wsgi.WSGIRequest 类的对象,其中包含了请求相关的所有数据。

    1. # Django FBV
    2. def index(request):
    3. request.method
    4. request.POST
    5. request.GET
    6. request.body
    7. # Django CBV
    8. from django.views import View
    9. class UserView(View):
    10. def get(self,request):
    11. request.method
    12. request.POST
    13. request.GET
    14. request.body

    而在使用drf框架时,视图中的request是rest_framework.request.Request类的对象,其是又对django的request进行了一次封装,包含了除django原request对象以外,还包含其他后期会使用的其他对象。对象 = (request, 其他数据)

    1. # rest_framework.request.Request 类
    2. class Request:
    3. """
    4. Wrapper allowing to enhance a standard `HttpRequest` instance.
    5. Kwargs:
    6. - request(HttpRequest). The original request instance. (django中的request)
    7. - parsers(list/tuple). The parsers to use for parsing the
    8. request content.
    9. - authenticators(list/tuple). The authenticators used to try
    10. authenticating the request's user.
    11. """
    12. def __init__(self, request, parsers=None, authenticators=None,negotiator=None, parser_context=None):
    13. self._request = request
    14. self.parsers = parsers or ()
    15. self.authenticators = authenticators or ()
    16. ...
    17. @property
    18. def query_params(self):
    19. """
    20. More semantically correct name for request.GET.
    21. """
    22. return self._request.GET
    23. @property
    24. def data(self):
    25. if not _hasattr(self, '_full_data'):
    26. self._load_data_and_files()
    27. return self._full_data
    28. def __getattr__(self, attr):
    29. try:
    30. return getattr(self._request, attr) # self._request.method
    31. except AttributeError:
    32. return self.__getattribute__(attr)

    所以,在使用drf框架开发时,视图中的request对象与原来的有些不同,例如:

    1. from rest_framework.views import APIView
    2. from rest_framework.response import Response
    3. from django.views import View
    4. from rest_framework.request import Request
    5. class UserView(APIView):
    6. def get(self, request, *args, **kwargs):
    7. # 通过对象的嵌套直接找到原request,读取相关值
    8. request._request.method
    9. request._request.GET
    10. request._request.POST
    11. request._request.body
    12. # 举例:
    13. content-type: url-form-encoded
    14. v1=123&v2=456&v3=999
    15. django一旦读取到这个请求头之后,就会按照 {"v1":123,"v2":456,"v3":999}
    16. content-type: application/json
    17. {"v1":123,"v2":456}
    18. request._request.POST
    19. request._request.body
    20. # 直接读取新request对象中的值,一般此处会对原始的数据进行一些处理,方便开发者在视图中使用。
    21. request.query_params # 内部本质上就是 request._request.GET
    22. request.data # 内部读取请求体中的数据,并进行处理,例如:请求者发来JSON格式,他的内部会对json字符串进行反序列化。
    23. # 通过 __getattr__ 去访问 request._request 中的值
    24. request.method

    可以发现,drf对原来的request对象进行了补充

    • request.data = request.POST/request.body
    • 也支持request.method

    底层源码实现:
    image-20210819150601089.png