欢迎来到赛兔子家园

drf中request对象和参数

request对象

drf中的request其实是对请求的再次封装,其目的就是在原来的request对象基础中再进行封装一些drf中需要用到的值。

views.py

from rest_framework.views import APIView

class UserView(APIView):
    def get(self,request):
        # drf的request对象
           print(request.query_params)
        print(request.data)
        print(request.auth)
        print(request.user)

        # django的request对象
                 print(request.GET)
        print(request.POST)
        print(request.method)
        print(request.path_info)
        return Response("....")

APIView源码

执行APIView类--->dispatch()方法

class APIView(View):
    ...
  def initialize_request(self, request, *args, **kwargs):
        """
        Returns the initial request object.
        """
        parser_context = self.get_parser_context(request)
        # 创建Request()对象后,返回
           return Request(
            request,
            parsers=self.get_parsers(),
            authenticators=self.get_authenticators(),
            negotiator=self.get_content_negotiator(),
            parser_context=parser_context
        )

  def dispatch(self, request, *args, **kwargs):
        """
        `.dispatch()` is pretty much the same as Django's regular dispatch,
        but with extra hooks for startup, finalize, and exception handling.
        """
         self.args = args
         self.kwargs = kwargs
         #django的request当成参数传递到initialize_request()方法
                  #initialize_request()方法作用对django中request对象再次封装,添加drf中需要用到的值。
                  request = self.initialize_request(request, *args, **kwargs)
         # 返回drf的request
                  self.request = request
         self.headers = self.default_response_headers  # deprecate?

...
请求参数

url中传递参数:http://127.0.0.1:8000/api/shipper/users/v2/23/

drf/urls.py

from django.urls import path,re_path

from .views import UserView

urlpatterns = [
    # url中传递参数version、pid
    path('users/<str:version>/<int:pid>/',UserView.as_view()),
    # 正则模式
    # re_path('users/(?P<version>\w+)/(?P<pid>\d+?)/',UserView.as_view())
]

视图中接收参数

views/UserView

from rest_framework.views import APIView

class UserView(APIView):
    def get(self,request,version,pid):
        print(version,pid)
        print(self.kwargs)
        print(self.args)
        return Response("....")

输出:

v2 23
{'version': 'v2', 'pid': 23}
()

 

posted on 2024-03-13 21:03  赛兔子  阅读(0)  评论(0编辑  收藏  举报

导航