在django的views中不論是用類方式還是用裝飾器方式來使用rest框架,django_rest_frame實現權限管理都需要兩個東西的配合: authentication_classes
和 permission_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
新聞熱點
疑難解答