django中APIView里的dispatch和as_view方法分析

yizhihongxing

位置:

from rest_framework.views import APIView

继承APIView类视图形式的路由:

path('booksapiview/', views.BooksAPIView.as_view()),  #在这个地方应该写个函数内存地址

继承APIView类的视图函数:

from rest_framework.views import APIView

class BooksAPIView(APIView):
    def get(self):
        pass
    
    def post(self):
        pass

APIView源码分析:

继承了APIView的视图函数,最终执行的是APIView里的as_view方法

@classmethod
def as_view(cls, **initkwargs):
    """
    Store the original class on the view function.

    This allows us to discover information about the view when we do URL
    reverse lookups.  Used for breadcrumb generation.
    """
    if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
        def force_evaluation():
            raise RuntimeError(
                'Do not evaluate the `.queryset` attribute directly, '
                'as the result will be cached and reused between requests. '
                'Use `.all()` or call `.get_queryset()` instead.'
            )

        cls.queryset._fetch_all = force_evaluation

    # 1.调用APIView父类,也就是View类中的as_view方法,将其返回值view在赋值给view
    view = super().as_view(**initkwargs)
    # 2.这里践行了一切皆对象的原则,将cls这个视图类给了view.cls,下面哪个也是一样
    view.cls = cls
    view.initkwargs = initkwargs

    # Note: session based authentication is explicitly CSRF validated,
    # all other authentication is CSRF exempt.
    # 3.这句话的意思就是以后所有继承APIView的试图函数都没有csrf认证了,和View类一样,APIview类的as_view方法最后也返回了view
    # 只不过apiview新增了去除csrf认证这里
    return csrf_exempt(view)

注意:上述返回的view内存地址,需要去找dispatch方法是先去apiview里找,而不是view类中的dispatch了

apiview里的dispatch方法分析:

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
    # 这里的request是self.initialize_request这个方法返回的新的由rest_framework中的Request类实例化产生的request对象
    request = self.initialize_request(request, *args, **kwargs)
    # 又把新的request对象给了视图函数中的request,从此,视图函数中的request就是新的request对象了
    self.request = request
    self.headers = self.default_response_headers  # deprecate?

    try:
        # 这里执行了apiview里的initial方法,这个方法里面包含了三大认证模块(重要)
        self.initial(request, *args, **kwargs)

        # Get the appropriate handler method
        # 三大认证过了之后,继续走,这里和view里面差不多,通过反射得到对应请求方式的函数地址
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(),
                              self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed

        # 将get请求或者其他请求方式执行之后的结果在给response模块
        response = handler(request, *args, **kwargs)

    # 这里是三大认证出异常的异常模块
    except Exception as exc:
        response = self.handle_exception(exc)

    # 渲染模块,对response这个相应结果在进行包装(就是在前端看到的由rest_framework渲染出来的数据结果页面)
    self.response = self.finalize_response(request, response, *args, **kwargs)
    # 返回该渲染模块
    return self.response

def initial(self, request, *args, **kwargs):
    # 该方法最重要的就是下面三句代码
    # Ensure that the incoming request is permitted
    # 这个是认证组件
    self.perform_authentication(request)
    # 这个是权限组件
    self.check_permissions(request)
    # 这个是频率组件
    self.check_throttles(request)

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:django中APIView里的dispatch和as_view方法分析 - Python技术站

(0)
上一篇 2023年4月2日 下午4:39
下一篇 2023年4月2日 下午4:39

相关文章

  • pycharm操作redis

    安装 在终端环境下输入: pip install redis pycharm操作redis之普通连接 # 1.导入模块 from redis import Redis # 2.实例化产生链接对象 conn = Redis() # 连接本地的redis # conn = Redis(host=”,port=”,password=”,) 连接远程的redi…

    2023年4月2日
    00
  • 序列化类高级用法之source、SerializerMethodField和断言assert

    序列化类高级用法之source 使用source,字段参数,可以修改序列化字段名字 原本序列化器中字段名,必须和表中的字段名一样,不一样会报错 我们可以通过source字段来改变序列化器中的字段名,使得前端在展示的时候也修改一下字段名!! source也可以做跨表查询,通过外键字段,表名点外键出去的字段名字 class BookSerializer(seri…

    2023年4月2日
    00
  • django的基本介绍与操作

    django的基本操作 1.django的安装 (1)在ubuntu上的安装 sudo pip3 install django==2.1.12(版本号) 检查安装是否成功: sudo pip3 freeze|grep -i ‘Django’ 有输出django==2.2.12 表示安装成功 (2)在windows上的安装 在终端执行 pip3 install…

    2023年4月2日
    00
  • 如何制作验证码

    推导步骤1:在img标签的src属性里放上验证码的请求路径 补充1.img的src属性: 1.图片路径 2.url 3.图片的二进制数据 补充2:字体样式 我们计算机上之所以可以输出各种各样的字体样式,其内部其实对应的是一个个以.ttf结尾的文件 由于img的src属性里可以放图片的二进制数据,因此我们可以在src里放上图片的请求路径,返回的是一个图片的二进…

    Python开发 2023年4月2日
    00
  • django中的auth模块与admin后台管理

    1. auth模块 在创建完django项目之后,执行数据库迁移之后,数据库里会增加很多新表,其中有一张名为auth_user的表,当访问django自带的路由admin的时候,需要输入用户名和密码,其参照的就是auth_user表 使用python3 manage.py crataesupperuser 可以创建超级管理员用户,同时在auth_user表里…

    2023年4月2日
    00
  • 进程、线程补充与协程相关介绍

    补充点 1.死锁 当你知道锁的使用抢锁必须要释放锁,其实你在操作锁的时候也极其容易产生死锁现象(整个程序卡死 阻塞) from threading import Thread, Lock import time mutexA = Lock() mutexB = Lock() # 类只要加括号多次 产生的肯定是不同的对象 # 如果你想要实现多次加括号等到的是相…

    Python开发 2023年4月2日
    00
  • rest_framework认证源码分析

    认证源码分析 位置 : APIVIew—-》dispatch方法—》self.initial(request, *args, **kwargs)—->有认证,权限,频率三个版块 分析: 只读认证源码: self.perform_authentication(request)—》self.perform_authentication(re…

    2023年4月2日
    00
  • django中有关ajax的部分

    Django_ajax 1 简介 AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML)。 同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求; 异步交互:客户…

    Python开发 2023年4月2日
    00
合作推广
合作推广
分享本页
返回顶部