在django的views中不管是用類方式仍是用裝飾器方式來使用rest框架,django_rest_frame實現權限管理都須要兩個東西的配合:authentication_classes
和 permission_classes
python
# 方式1: 裝飾器
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import AllowAny
from 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, BasicAuthentication
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
class 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文件,最原始的默認值均可以在裏面找到: django
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': (
'your_authentication_class_path',
),
...
}
複製代碼
在rest的settings文件中,獲取屬性時,會優先加載項目的settings文件中的設置,若是項目中沒有的,才加載本身的默認設置:api
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)
複製代碼
APISettings
類中獲取屬性時優先獲取項目的settings文件中REST_FRAMEWORK
對象的值,沒有的再找本身的默認值@property
def user_settings(self):
if not hasattr(self, '_user_settings'):
# _user_settings默認爲加載項目settings文件中的REST_FRAMEWORK對象
self._user_settings = getattr(settings, 'REST_FRAMEWORK', {})
return self._user_settings
def __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
複製代碼
在rest中settings中,能自動檢測項目settings的改變,並從新加載本身的配置文件: bash
rest框架是如何使用authentication_classes
和permission_classes
,並將兩者配合起來進行權限管理的呢?框架
urls.py
中使用該類的as_view
方法來構建router# views.py
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
class ExampleAPIView(APIView):
permission_classes = (IsAuthenticated,)
...
# -----------------------------
from django.conf.urls import url, include
from .views import ExampleAPIView
urlpatterns = [
url(r'^example/(?P<example_id>[-\w]+)/examples/?$',
ExampleAPIView.as_view()),
]
複製代碼
在咱們調用APIVIEW.as_view()
的時候,該類會調用父類的同名方法: ui
父類的同名方法中,調用了dispatch方法: this
rest 重寫 了該方法,在該方法中對requset作了一次服務端初始化(加入驗證信息等)處理 url
在權限管理中會使用默認的或是你指定的權限認證進行驗證: 這裏只是作驗證並存儲驗證結果,這裏操做完後authentication_classes的做用就完成了。驗證結果會在後面指定的permission_classes
中使用!spa
def get_authenticators(self):
""" Instantiates and returns the list of authenticators that this view can use. """
return [auth() for auth in self.authentication_classes]
複製代碼
經過指定的permission_classes肯定是否有當前接口的訪問權限:3d
class IsAuthenticatedOrReadOnly(BasePermission):
""" The request is authenticated as a user, or is a read-only request. """
def has_permission(self, request, view):
return (
request.method in SAFE_METHODS or
request.user and
request.user.is_authenticated
)
複製代碼
最後,無論有沒有使用permission_classes來決定是否能訪問,默認的或是你本身指定的authentication_classes都會執行並將權限結果放在request中!