Request

文档

from rest_framework.request import Request

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

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

Request对象的数据是自动根据前端发送数据的格式进行解析之后的结果。

无论前端发送的哪种格式的数据,我们都可以以统一的方式读取数据。

常用属性

1)data

request.data返回解析之后的请求体数据。类似于Django中标准的request.POST属性,但提供如下特性:

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

    from rest_framework.request import Request
    class Request:
    
      @property
      def data(self):
          if not _hasattr(self, '_full_data'):
              self._load_data_and_files()
          return self._full_data
    
      def _load_data_and_files(self):
          """
          Parses the request content into `self.data`.
          """
          if not _hasattr(self, '_data'):
              self._data, self._files = self._parse()
              if self._files:
                  self._full_data = self._data.copy()
                  self._full_data.update(self._files)
              else:
                  self._full_data = self._data
    
              # if a form media type, copy data & files refs to the underlying
              # http request so that closable objects are handled appropriately.
              if is_form_media_type(self.content_type):
                  self._request._post = self.POST
                  self._request._files = self.FILES
    

2)query_params

request.query_params与Django标准的request.GET相同,只是更换了更正确的名称而已。

from rest_framework.request import Request

class Request:
    @property
    def query_params(self):
        """
        More semantically correct name for request.GET.
        """
        return self._request.GET