• 补充01 Django 类视图


    视图

    函数视图[Function Base View]

    以函数的方式定义的视图称为函数视图,函数视图便于理解。但是遇到一个视图对应的路径提供了多种不同HTTP请求方式的支持时,便需要在一个函数中编写不同的业务逻辑,代码可读性与复用性都不佳。

     def register(request):
        """处理注册"""
    
        # 获取请求方法,判断是GET/POST请求
        if request.method == 'GET':
            # 处理GET请求,返回注册页面
            return render(request, 'register.html')
        else:
            # 处理POST请求,实现注册逻辑
            return HttpResponse('这里实现注册逻辑')

    类视图[Class Base View]

    在Django中也可以使用类来定义一个视图,称为类视图

    使用类视图可以将视图对应的不同请求方式以类中的不同方法来区别定义。如下所示

    """
    # django的类视图一共提供了多个以http请求方法命名的类方法给我们使用。
    # 当客户端使用不同的http请求方法访问当前视图类,django会根据请求方法访问到当前类视图中的同名对象方法中。
    # http常用请求方法
    # GET    客户端向服务端请求读取数据
    # POST   客户端向服务器请求创建数据
    # PUT    客户端向服务器请求修改数据[全部]
    # PATCH  客户端向服务器请求修改数据[修改部分数据]
    # DELETE 客户端向服务器请求删除数据
    """
    from django.views import View
    from django.http.response import HttpResponse
    class UserView(View):
        def post(self,request):
            print("客户端进行post请求")
            return HttpResponse("post")
    
        def get(self,request):
            print("客户端进行get请求")
            return HttpResponse("get")
    
        def put(self,request):
            print("客户端进行put请求")
            return HttpResponse("put")
    
        def delete(self,request):
            print("客户端进行delete请求")
            return HttpResponse("delete")

    类视图的好处:

    • 代码可读性好

    • 类视图相对于函数视图有更高的复用性, 如果其他地方需要用到某个类视图的某个特定逻辑,直接继承该类视图即可

    类视图使用

    定义类视图需要继承自Django提供的父类View,可使用from django.views.generic import View或者from django.views.generic.base import View 导入,定义方式如上所示。

    配置路由时,使用类视图的as_view()方法来添加

    from django.urls import path
    from . import views
    urlpatterns = [
        path("cls/", views.UserView.as_view() ),
    ]
    class View:######源码分析:类视图调用关系 1、 path("cls/", views.UserView.as_view() ),  UserView继承了View类 并调用View的类方法as_view
        """
        Intentionally simple parent class for all views. Only implements
        dispatch-by-method and simple sanity checking.
        """
    
        http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
    
        def __init__(self, **kwargs):
            """
            Constructor. Called in the URLconf; can contain helpful extra
            keyword arguments, and other things.
            """
            # Go through keyword arguments, and either save their values to our
            # instance, or raise an error.
            for key, value in kwargs.items():
                setattr(self, key, value)
    
        @classonlymethod
        def as_view(cls, **initkwargs):
            """Main entry point for a request-response process."""
            for key in initkwargs:
                if key in cls.http_method_names:
                    raise TypeError("You tried to pass in the %s method name as a "
                                    "keyword argument to %s(). Don't do that."
                                    % (key, cls.__name__))
                if not hasattr(cls, key):
                    raise TypeError("%s() received an invalid keyword %r. as_view "
                                    "only accepts arguments that are already "
                                    "attributes of the class." % (cls.__name__, key))
    
            def view(request, *args, **kwargs):
                self = cls(**initkwargs)
                if hasattr(self, 'get') and not hasattr(self, 'head'):
                    self.head = self.get
                self.setup(request, *args, **kwargs)
                if not hasattr(self, 'request'):
                    raise AttributeError(
                        "%s instance has no 'request' attribute. Did you override "
                        "setup() and forget to call super()?" % cls.__name__
                    )
                return self.dispatch(request, *args, **kwargs)######3、view函数中调用了类方法   dispatch
            view.view_class = cls
            view.view_initkwargs = initkwargs
    
            # take name and docstring from class
            update_wrapper(view, cls, updated=())
    
            # and possible attributes set by decorators
            # like csrf_exempt from dispatch
            update_wrapper(view, cls.dispatch, assigned=())
            return view   #######  2、执行as_view函数时返回view函数变量
    
        def setup(self, request, *args, **kwargs):
            """Initialize attributes shared by all view methods."""
            self.request = request
            self.args = args
            self.kwargs = kwargs
    
        def dispatch(self, request, *args, **kwargs):##############相当于路由分发
            # Try to dispatch to the right method; if a method doesn't exist,
            # defer to the error handler. Also defer to the error handler if the
            # request method isn't on the approved list.
            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
            return handler(request, *args, **kwargs)######4、  判断UserView类中是否有 请求方式的例如:POST GET 等请求  request.method.lower() 变成小写 有着返回该类方法的执行结果
    
        def http_method_not_allowed(self, request, *args, **kwargs):
            logger.warning(
                'Method Not Allowed (%s): %s', request.method, request.path,
                extra={'status_code': 405, 'request': request}
            )
            return HttpResponseNotAllowed(self._allowed_methods())
    
        def options(self, request, *args, **kwargs):
            """Handle responding to requests for the OPTIONS HTTP verb."""
            response = HttpResponse()
            response['Allow'] = ', '.join(self._allowed_methods())
            response['Content-Length'] = '0'
            return response
    
        def _allowed_methods(self):
            return [m.upper() for m in self.http_method_names if hasattr(self, m)]
    源码分析:类视图调用关系

    类视图使用装饰器

    为类视图添加装饰器,可以使用三种方法。

    为了理解方便,我们先来定义一个为函数视图准备的装饰器(在设计装饰器时基本都以函数视图作为考虑的被装饰对象),及一个要被装饰的类视图。

    方式一:

    from django.shortcuts import render
    
    # Create your views here.
    
    from django.views import View
    from django.http.response import HttpResponse
    ####普通的装饰器调用
    def my_decorator(func):
        def wrapper(request, *args, **kwargs):
            print('自定义装饰器被调用了')
            print('请求路径%s' % request.path)
            return func(request, *args, **kwargs)
        return wrapper
    
    @my_decorator
    def decoratordemo(request):
        return HttpResponse("函数视图")
    
    """不能直接在类视图的方法中直接使用装饰器,会出现参数位置的错误,会多传递一个self当前对象给装饰器,从而导致错误"""
    # class UAPI(View):
    #     @my_decorator
    #     def get(self,request):
    #         return HttpResponse("类视图使用装饰器")
    
    
    class UAPI2(View):
        def get(self,request):
            return HttpResponse("类视图使用装饰器")
    app01/views.py
    from django.contrib import admin
    from django.urls import path
    from app01 import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        # path("cls/", views.UserView.as_view() ),
        path("fbv/", views.decoratordemo),
        path("cbv2/", views.my_decorator(views.UAPI2.as_view())),  # 在路由中使用装饰器不好!不好维护,不易理解
    ]
    urls.py

     

    def my_decorator(func):
        def wrapper(self,request, *args, **kwargs):
            print('自定义装饰器被调用了')
            print('请求路径%s' % request.path)
            return func(self,request, *args, **kwargs)
        return wrapper
    
    # @my_decorator
    # def decoratordemo(request):
    #     return HttpResponse("函数视图")
    
    """不能直接在类视图的方法中直接使用装饰器,会出现参数位置的错误,会多传递一个self当前对象给装饰器,从而导致错误"""
    class UAPI(View):
        @my_decorator
        def get(self,request):
            return HttpResponse("类视图使用装饰器")
    解决方案

     在类视图中使用为函数视图准备的装饰器时,不能直接添加装饰器,需要使用method_decorator将其转换为适用于类视图方法的装饰器。

    method_decorator装饰器还支持使用name参数指明被装饰的方法

     方式二:

    from django.shortcuts import render
    
    # Create your views here.
    
    from django.views import View
    from django.http.response import HttpResponse
    ####普通的装饰器调用
    def my_decorator(func):
        def wrapper(request, *args, **kwargs):
            print('自定义装饰器被调用了')
            print('请求路径%s' % request.path)
            return func(request, *args, **kwargs)
        return wrapper
    
    """要装饰类方法,可以使用django.utils.decorators.method_decorator装饰器来装饰"""
    from django.utils.decorators import method_decorator
    #初版本
    # class UAPI3(View):
    #     @method_decorator(my_decorator)
    #     def get(self,request):
    #         return HttpResponse("类视图get方法使用装饰器")
    #
    #     @method_decorator(my_decorator)
    #     def post(self,request):
    #         return HttpResponse("类视图post方法使用装饰器")
    
    #升级版本
    # 在开发中,一般不建议在类中的方法上面添加装饰器,而是建议写在类的前面
    # @method_decorator(my_decorator,name="get")
    # @method_decorator(my_decorator,name="post")
    # class UAPI3(View):
    #     def get(self,request):
    #         return HttpResponse("类视图get方法使用装饰器")
    #
    #     def post(self,request):
    #         return HttpResponse("类视图post方法使用装饰器")
    
    #升级版本
    """如果同一个类中所有方法公用一个装饰器,把装饰器添加到dispatch中,因为类视图中任意一个方法都会执行到as_view,as_view里面必然调用了当前对象的dispatch"""
    @method_decorator(my_decorator,name="dispatch")
    class UAPI3(View):
        def get(self,request):
            return HttpResponse("类视图get方法使用装饰器")
    
        def post(self,request):
            return HttpResponse("类视图post方法使用装饰器")
    app01/views.py
    from django.contrib import admin
    from django.urls import path
    from app01 import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        path("cbv3/", views.UAPI3.as_view()),
    ]
    urls

    构造Mixin扩展类

    方式三:

    from django.shortcuts import render
    
    # Create your views here.
    
    from django.views import View
    from django.http.response import HttpResponse
    ####普通的装饰器调用
    def my_decorator(func):
        def wrapper(request, *args, **kwargs):
            print('自定义装饰器被调用了')
            print('请求路径%s' % request.path)
            return func(request, *args, **kwargs)
        return wrapper
    
    
    """要装饰类方法,可以使用django.utils.decorators.method_decorator装饰器来装饰"""
    from django.utils.decorators import method_decorator
    
    """在多个类视图中如果要公用代码,可以使用多继承[Mixin扩展类]"""
    @method_decorator(my_decorator,name='dispatch')
    class BaseView(View):
        pass
    
    class UAPI4(BaseView):
        def get(self,request):
            return HttpResponse("类视图4get方法使用装饰器")
    
        def post(self,request):
            return HttpResponse("类视图4post方法使用装饰器")
    
    
    class MyDecoratorMixin(object):
        @classmethod
        def as_view(cls, *args, **kwargs):
            print( super() ) # View
            view = super().as_view(*args, **kwargs)
            # 进行装饰
            view = my_decorator(view)
            return view
    
    class DemoView(MyDecoratorMixin, View):
        def get(self, request):
            print('get方法')
            return HttpResponse('getok')
    
        def post(self, request):
            print('post方法')
            return HttpResponse('postok')
    app01/views.py
    from django.contrib import admin
    from django.urls import path
    from app01 import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        path("cbv4/", views.UAPI4.as_view()),
        path("cbv5/", views.DemoView.as_view()),
    ]
    urls.py

     

  • 相关阅读:
    项目经验:如何做到不和产品打起来
    leetcode-剑指30-OK
    leetcode-剑指05-OK
    leetcode-剑指58-OK
    leetcode-剑指28-OK
    leetcode-剑指53-I
    leetcode-剑指18-OK
    leetcode-剑指15-OK
    leetcode-剑指27-OK
    leetcode-剑指17-OK
  • 原文地址:https://www.cnblogs.com/linux985/p/10935461.html
Copyright © 2020-2023  润新知