rest framework之APIView

一、rest framework配置

1、安装rest framework

在django环境中安装rest-framework框架:

(automatic) C:UsersAdministrator>pip install djangorestframework

2、在django项目中进行配置

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework', #配置djangorestframework
]

二、rest_framework下的APIView

  rest framework中的APIView是在CBV的基础上进行扩展的,CNV模式实际上时在dispatch方法中进行分发的,而APIView就是在dispatch中除了分发方法外,还扩展重构

request对象。

from rest_framework.views import APIView #导入APIView

urls.py

from crm import views
from django.conf.urls import url,include

url(r'^login',views.LoginView.as_view(), name='login'),#源码入口

views.py

class LoginView(APIView):

    def get(self,request):
        pass

    def post(self,request):
        pass

可以看到执行as_view方法,自己没有去父类中寻找:

class APIView(View):#继承的View就是CBV中的View
     """
     ...

     """
    #返回的是view方法,而view方法又是执行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.
        """
        ...
       
        view = super(APIView, cls).as_view(**initkwargs) #执行父类as_view
        view.cls = cls
        view.initkwargs = initkwargs

        # Note: session based authentication is explicitly CSRF validated,
        # all other authentication is CSRF exempt.
        return csrf_exempt(view)
    

  可以看到这里APIView中的as_view实际执行的还是CBV中的as_view方法,最后执行的就是dispatch方法,先去LoginView中找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
#rest-framework重构request对象 request = self.initialize_request(request, *args, **kwargs) self.request = request #将分发方法的request进行赋值,此时就是重构的request self.headers = self.default_response_headers # deprecate? try: self.initial(request, *args, **kwargs) # Get the appropriate handler method #这里和CBV一样进行方法的分发 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 response = handler(request, *args, **kwargs) except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response

  从上面可以看到rest framework中的APIView不仅有CBV模式的特性而且,又新加了自己的东西,主要就是request的重构,可以看看request重构了什么,从initialize_request的返回值可以看出有对原request进行了封装、加入认证等:

 def initialize_request(self, request, *args, **kwargs):
        """
        Returns the initial request object.
        """
        parser_context = self.get_parser_context(request)

        return Request(
            request, #传入原request
            parsers=self.get_parsers(),
            authenticators=self.get_authenticators(), #认证
            negotiator=self.get_content_negotiator(),
            parser_context=parser_context
        )

此时dispatch中分发方法的request不是原request了,是已经重构的request:

#原request的调用方式
request._request

而现在重构的request,GET或者其他请求数据:

#如果是GET请求就使用
request.query_params

#如果是POST或者其它请求就使用
request.data

总结:

原文地址:https://www.cnblogs.com/shenjianping/p/11383586.html