Django restframework用户权限认证组件增加及源码分析
用户权限验证源码剖析,和用户登录验证有点相似,但是为了增加记忆,有必要再一次添加,
注意:一定要跟着博主的解说再看代码的中文注释及其下面的一行代码!!!
1、准备一个路由和视图类,全局路由配置暂时忽略,当流程执行到下面的url:groupsSelectAll——> GroupsView的视图类下的as_view()方法
from django.conf.urls import url
from . import views
app_name = '[words]'
urlpatterns = [
url(r'groupsSelectAll/', views.GroupsView.as_view(), name="groupsSelectAll"), # 词组信息查询所有
]
class GroupsView(APIView):
def get(self, request):
conditions = {
"id": request.query_params.get("wid"),
"name": request.query_params.get("name"),
"start_time": request.query_params.get("start_time"),
"end_time": request.query_params.get("end_time"),
}
res = DataManager.select_by_conditions("words_groups", None, **conditions)
return Response(data={"code": 200, "result": res})
2、但是GroupsView类下没有as_view方法,这时就要去它的父类APIView查看(点进去看as_view方法),这里博主只复制方法源代码,大家只需要看中文注释及其下的代码语句。在这个方法中值得一提的是super关键字,如果请求视图类(就是GroupsView类,如果继承了多个父类)还有另一个父类,它先会查看这个父类是否有as_view方法。在这里它是会执行APIView的父类View中的as_view方法,然后我们再次查看父类View的as_view方法。第一个as_view方法是APIView类的,第二个as_view方法是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. """ if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet): def force_evaluation(): raise RuntimeError( 'Do not evaluate the `.queryset` attribute directly, ' 'as the result will be cached and reused between requests. ' 'Use `.all()` or call `.get_queryset()` instead.' ) cls.queryset._fetch_all = force_evaluation # 执行父类的as_view方法 view = super(APIView, cls).as_view(**initkwargs) view.cls = cls view.initkwargs = initkwargs # Note: session based authentication is explicitly CSRF validated, # all other authentication is CSRF exempt. return csrf_exempt(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)) # 执行view方法 def view(request, *args, **kwargs): # 这里的cls就是我们的请求视图类,显而易见,这个self是请求试图类的对象 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 # 然后这里就是执行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 view
3、我们在第二个as_view方法中可以知道self是我们的请求视图类的对象,通过这个self调用dispatch方法,请求视图类中没有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 # 这里是对原生的request加工处理,返回一个新的request对象 request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: # 初始化(用户登录认证,权限验证,访问频率限制) self.initial(request, *args, **kwargs) # Get the appropriate handler method if request.method.lower() in self.http_method_names: # 通过python的反射机制反射到请求视图类的方法名称 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
4、其他代码不用看,我们直接看initial方法,因为这个initial方法有权限验证的功能。
def initial(self, request, *args, **kwargs): """ Runs anything that needs to occur prior to calling the method handler. """ self.format_kwarg = self.get_format_suffix(**kwargs) # Perform content negotiation and store the accepted info on the request neg = self.perform_content_negotiation(request) request.accepted_renderer, request.accepted_media_type = neg # Determine the API version, if versioning is in use. version, scheme = self.determine_version(request, *args, **kwargs) request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted # 用户验证的方法,这个request 是加工之后的request self.perform_authentication(request) # 用户权限验证 self.check_permissions(request) # 用户访问频率限制 self.check_throttles(request)
5、这就到了我们的用户权限验证的戏码了。博主添加APIView部分代码,即check_permission方法用到的代码。我们可以查看代码中的self.check_permissions(request),点进去查看check_permissions()方法,可以看到有get_permissions方法,这个方法有self.permission_classes变量,即self.permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES,然后这里也和【上一篇的用户登录验证】很相似,就是请求视图类中如果没有这个变量名及值(值是一个列表),就会使用全局配置文件中的REST_FRAMEWORK={"DEFAULT_PERMISSION_CLASSES":["权限验证类的全路径"]},或者我们在请求视图类中添加这个变量及值
class APIView(View): # 如果请求视图类中没有这个变量和值,就会使用全局配置文件的值 permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES def check_permissions(self, request): """ Check if the request should be permitted. Raises an appropriate exception if the request is not permitted. """ # 循环权限类的对象 for permission in self.get_permissions(): # 执行对象下的has_permission()方法,验证是否有权限(默认是有权限) if not permission.has_permission(request, self): self.permission_denied( request, message=getattr(permission, 'message', None) ) def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ # 返回的是一个权限类的对象 return [permission() for permission in self.permission_classes] def permission_denied(self, request, message=None): """ If request is not permitted, determine what kind of exception to raise. """ # 有权限类,但是没有登录,就抛出用户没有登录的异常 if request.authenticators and not request.successful_authenticator: raise exceptions.NotAuthenticated() # 抛出没有权限的异常 raise exceptions.PermissionDenied(detail=message)
6、在上面的APIView类中会执行到if not permission.has_permission(request, self),我们可以直接点进去查看has_permission方法。一般我们自定义这个用户权限验证类的话我们一般需要继承BasePermission类,这样我们直接重写has_permission方法,里面的需求就是验证时候当前登录的用户是否具有某个模块的权限。像这样我们可以自定义一个只有充值称为VIP或者SVIP用户访问权限的类(这只是我的设想)