Django源码分析--01类视图

2018-07-05  本文已影响0人  梦醒家先生

1.类视图的引入

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

def register(request):
    """处理注册"""

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

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

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

from django.views.generic import View

class RegisterView(View):
    """类视图:处理注册"""
      '''
      1. 继承View类中的as_view方法:
      2. cls:代表当前的继承类RegisterView
      def as_view(cls, **initkwargs):
           ....
           
          return view
      '''
    def get(self, request):
        """处理GET请求,返回注册页面"""
        return render(request, 'register.html')

    def post(self, request):
        """处理POST请求,实现注册逻辑"""
        return HttpResponse('这里实现注册逻辑')

类视图的好处:

2 类视图使用

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

urlpatterns = [
    # 视图函数:注册
    # url(r'^register/$', views.register, name='register'),
    # 类视图:注册
    url(r'^register/$', views.RegisterView.as_view(), name='register'),
]

3 类视图原理

class A(object):

    def get(self, request):

        print(request)

a = A()
# 传入a对象,来查询-->类A的对象中有没有'get'这个方法或者属性-->查询到以后返回给func
func = getattr(a, 'get')

# 查询到A类中有get方法,就执行类方法get
func(66666)

# 执行结果
66666
class View(object):
    """
    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 six.iteritems(kwargs):
            setattr(self, key, value)

类属性:http_method_names :储存了所有请求方法

@classonlymethod
    def as_view(cls, **initkwargs):
        '''
        # cls 代表当前类,类视图继承View以后,调用as_view,就代表类继承类
        '''
        """
        Main entry point for a request-response process.
        请求-响应过程的主要入口点。
        """
        for key in initkwargs:
            '''
            # 判断继承类中request请求对象获取的请求方式
            '''
            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.request = request
            self.args = args
            self.kwargs = kwargs
          '''
            # view接收类方法dispatch引用
          '''
            return self.dispatch(request, *args, **kwargs)
        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给as_view的方法view引用,方法view接收dispatch类方法引用
        '''
        return view
'''
# 对不同的请求方式,返回不同的请求结果
'''
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)
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)

request.method获取请求方式,将请求参数lower()转换小写,是否在类属性:http_method_names

上一篇下一篇

猜你喜欢

热点阅读