首页 > 编程 > Python > 正文

Django-Rest-Framework 权限管理源码浅析(小结)

2020-02-15 23:38:55
字体:
来源:转载
供稿:网友

在django的views中不论是用类方式还是用装饰器方式来使用rest框架,django_rest_frame实现权限管理都需要两个东西的配合: authentication_classespermission_classes

# 方式1: 装饰器from rest_framework.decorators import api_view, authentication_classes, permission_classesfrom rest_framework.authentication import SessionAuthentication, BasicAuthenticationfrom rest_framework.permissions import AllowAnyfrom rest_framework.response import Response@api_view(["GET", ])@permission_classes([AllowAny,])@authentication_classes([SessionAuthentication, BasicAuthentication])def test_example(request): content = {   'user': unicode(request.user), # `django.contrib.auth.User` instance.   'auth': unicode(request.auth), # None  }  return Response(content)# ------------------------------------------------------------# 方式2: 类from rest_framework.authentication import SessionAuthentication, BasicAuthenticationfrom rest_framework.permissions import AllowAnyfrom rest_framework.response import Responsefrom rest_framework.views import APIViewclass ExampleView(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (AllowAny,) def get(self, request, format=None):  content = {   'user': unicode(request.user), # `django.contrib.auth.User` instance.   'auth': unicode(request.auth), # None  }  return Response(content)

上面给出的是权限配置的默认方案,写和不写没有区别。 rest框架有自己的settings文件 ,最原始的默认值都可以在里面找到:

说道rest的settings文件,要覆盖其中的默认行为,特别是权限认证行为,我们只需要在 项目settings文件

中指定你自己的类即可:

REST_FRAMEWORK = { ... 'DEFAULT_AUTHENTICATION_CLASSES': (  'your_authentication_class_path', ), ...}

在rest的settings文件中,获取属性时,会优先加载项目的settings文件中的设置,如果项目中没有的,才加载自己的默认设置:

初始化api_settings对象

api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)

APISettings 类中获取属性时优先获取项目的settings文件中 REST_FRAMEWORK 对象的值,没有的再找自己的默认值

@propertydef user_settings(self): if not hasattr(self, '_user_settings'):  # _user_settings默认为加载项目settings文件中的REST_FRAMEWORK对象  self._user_settings = getattr(settings, 'REST_FRAMEWORK', {}) return self._user_settingsdef __getattr__(self, attr): if attr not in self.defaults:  raise AttributeError("Invalid API setting: '%s'" % attr) try:  # Check if present in user settings  # 优先加载user_settings,即项目的settings文件,没有就用默认  val = self.user_settings[attr] except KeyError:  # Fall back to defaults  val = self.defaults[attr] # Coerce import strings into classes if attr in self.import_strings:  val = perform_import(val, attr) # Cache the result self._cached_attrs.add(attr) setattr(self, attr, val) return val            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表