python - Django mixins.py 和 super() 函数
问题描述
我尝试了解 mixins.py 中 super() 函数的行为
部分源码: (django\contrib\auth\mixins.py)
class AccessMixin:
"""
Abstract CBV mixin that gives access mixins the same customizable
functionality.
"""
login_url = None
permission_denied_message = ''
raise_exception = False
redirect_field_name = REDIRECT_FIELD_NAME
def get_login_url(self):
"""
Override this method to override the login_url attribute.
"""
login_url = self.login_url or settings.LOGIN_URL
if not login_url:
raise ImproperlyConfigured(
'{0} is missing the login_url attribute. Define {0}.login_url, settings.LOGIN_URL, or override '
'{0}.get_login_url().'.format(self.__class__.__name__)
)
return str(login_url)
def get_permission_denied_message(self):
"""
Override this method to override the permission_denied_message attribute.
"""
return self.permission_denied_message
def get_redirect_field_name(self):
"""
Override this method to override the redirect_field_name attribute.
"""
return self.redirect_field_name
def handle_no_permission(self):
if self.raise_exception or self.request.user.is_authenticated:
raise PermissionDenied(self.get_permission_denied_message())
path = self.request.build_absolute_uri()
resolved_login_url = resolve_url(self.get_login_url())
# If the login url is the same scheme and net location then use the
# path as the "next" url.
login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if (
(not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)
):
path = self.request.get_full_path()
return redirect_to_login(
path,
resolved_login_url,
self.get_redirect_field_name(),
)
class LoginRequiredMixin(AccessMixin):
"""Verify that the current user is authenticated."""
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs)
看不懂,最后一排
官方文档说 super() 调用父类。
因此,在这种情况下,它(super())将在 LoginRequiredMixin 的父类中搜索一个dispatch()方法,即 AccessMixin。但是AccessMixin里面没有dispatch()方法,所以肯定会报这样的错误:
AttributeError: 'super' object has no attribute 'dispatch'
但这一切都有效)而且我无法理解该行的方式和原因,以及该行的作用。谢谢)
解决方案
推荐阅读
- php - 开发 Directus 扩展时如何设置单元测试?
- python - 如何使用 python 更改用户的 shell 当前目录?(ubuntu/linux)
- python - Python Pandas 基于 case 语句分组
- javascript - 如何测试反应钩子方法?
- flutter - StatefulWidget 中的 setState() 无法正常工作
- asp.net-core - 如果与 JWT 不记名身份验证一起使用,Asp.Net 核心 Web API 防伪验证将失败
- java - Aggregation和Association在实现上的区别
- visual-studio-code - VSCode 终端中的前向/后向词
- c++ - 为什么在使用我的 auto_ptr 样式类访问结构成员时会得到“未识别的标识符”?
- c# - 处理 DOTS 中的非自定义组件