zoukankan      html  css  js  c++  java
  • rest-framework之APIView

    一 安装djangorestframework

    方式一:pip3 install djangorestframework

    方式二:pycharm图形化界面安装

    方式三:pycharm命令行下安装(装在当前工程所用的解释器下)

    二  djangorestframework的APIView分析

    复制代码
     @classmethod
        def as_view(cls, **initkwargs):
      #这句话执行完成 view闭包函数的内存地址
    """ 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      #调用父类(view)的as_view view = super(APIView, cls).as_view(**initkwargs) view.cls = cls view.initkwargs = initkwargs       
          view = csrf_exempt(view)#局部禁用csrf
    # Note: session based authentication is explicitly CSRF validated, # all other authentication is CSRF exempt. return csrf_exempt(view)
    复制代码
    复制代码
     
    #请求来了会执行上面返回的view()---->self.dispatch(APIView的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,封装进新的Request对象(drf的Request) request
    = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: self.initial(request, *args, **kwargs) # Get the appropriate handler method 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           #这个request新的request,是drf中Request对象
              #response是原生response
    response
    = handler(request, *args, **kwargs) except Exception as exc:
          #全局异常 response
    = self.handle_exception(exc)       #把原生的reponse包装了一下 self.response = self.finalize_response(request, response, *args, **kwargs) return self.response
    复制代码
    复制代码
        def initialize_request(self, request, *args, **kwargs):
            """
            Returns the initial request object.
            """
            parser_context = self.get_parser_context(request)
    
            return Request(
                request,
                parsers=self.get_parsers(),
                authenticators=self.get_authenticators(),
                negotiator=self.get_content_negotiator(),
                parser_context=parser_context
            )
    复制代码
    复制代码
        def initial(self, request, *args, **kwargs):
            """
            Runs anything that needs to occur prior to calling the method handler.
            """
            self.format_kwarg = self.get_format_suffix(**kwargs)
    
            # Perform content negotiation and store the accepted info on the request
            neg = self.perform_content_negotiation(request)
            request.accepted_renderer, request.accepted_media_type = neg
    
            # Determine the API version, if versioning is in use.
            version, scheme = self.determine_version(request, *args, **kwargs)
            request.version, request.versioning_scheme = version, scheme
    
            # Ensure that the incoming request is permitted
        #重点(频率,认证,权限)
    self.perform_authentication(request) self.check_permissions(request) self.check_throttles(request)
    复制代码

    三 djangorestframework的Request对象简单介绍

    每天逼着自己写点东西,终有一天会为自己的变化感动的。这是一个潜移默化的过程,每天坚持编编故事,自己不知不觉就会拥有故事人物的特质的。 Explicit is better than implicit.(清楚优于含糊)
  • 相关阅读:
    关于View的onMeasure()、onSizeChanged()、onLayout()、onDraw()调用顺序
    Android事件分发机制完全解析,带你从源码的角度彻底理解(上)
    Android事件分发机制完全解析,带你从源码的角度彻底理解(下)
    自定义View经常重写的方法
    为自己的自定义View添加额外属性
    自定义View常用的获取宽高信息
    用工厂流水线的方式来理解 RxJava 的概念
    发布开源项目到Maven 中心仓库
    Android应用架构之Retrofit使用
    docker新手入门(基本命令以及介绍)
  • 原文地址:https://www.cnblogs.com/kylin5201314/p/13967049.html
Copyright © 2011-2022 走看看