Django类视图与Mixin

本文探讨了Django中如何将类视图通过CBV.as_view()转化为函数视图,解释了dispatch方法在类视图中的作用。同时,介绍了在类视图中如何使用Mixin,如LoginRequiredMixin和PermissionRequiredMixin,及其工作原理,包括MRO方法的调用顺序。此外,还讨论了处理权限异常的情况,以及如何自定义登录重定向URL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在上一篇Django处理http请求流程剖析中,笔者详细地说明了Django框架是如何根据WSGI协议处理一个Http请求的。其中,处理开发者自行定义的View的代码如下:

# django.core.handlers.base.py

# 路由解析
resolver_match = resolver.resolve(request.path_info)
callback, callback_args, callback_kwargs = resolver_match
request.resolver_match = resolver_match

# 执行view函数
if response is None:
    wrapped_callback = self.make_view_atomic(callback)
    try:
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
    except Exception as e:
        response = self.process_exception_by_middleware(e, request)

如果开发者使用的是函数视图(FBV),这段代码非常好理解,wrapped_back就是该函数视图,直接调用即可。

但是如果是类视图呢,Django是如何将类视图转化为一个函数呢?

CBV.as_view()

在Django的路由中为url指定view的时候,如果为类视图(所有类视图都需要继承于基类View),则需要使用as_view方法将类视图转化为一个函数,接下来笔者就分析一下as_view方法的源码。

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)

    # as_view方法经过类方法装饰器,是一个类方法
    @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))

        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值