1. 程式人生 > 實用技巧 >Django Rest Framework元件:許可權模組BasePermission

Django Rest Framework元件:許可權模組BasePermission

這裡給出區域性配置寫法,全域性配置需要在setting檔案中寫入。

urls.py

from django.conf.urls import url, include
from 應用名.views import TestView

urlpatterns = [
    url(r'^test/', TestView.as_view()),
]

views.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import
Response from rest_framework.authentication import BaseAuthentication from rest_framework.permissions import BasePermission from rest_framework.request import Request from rest_framework import exceptions token_list = [ 'sfsfss123kuf3j123', 'asijnfowerkkf9812', ] class TestAuthentication(BaseAuthentication):
def authenticate(self, request): """ 使用者認證,如果驗證成功後返回元組: (使用者,使用者Token) :param request: :return: None,表示跳過該驗證; 如果跳過了所有認證,預設使用者和Token和使用配置檔案進行設定 self._authenticator = None if api_settings.UNAUTHENTICATED_USER: self.user = api_settings.UNAUTHENTICATED_USER() # 預設值為:匿名使用者 else: self.user = None if api_settings.UNAUTHENTICATED_TOKEN: self.auth = api_settings.UNAUTHENTICATED_TOKEN()# 預設值為:None else: self.auth = None (user,token)表示驗證通過並設定使用者名稱和Token; AuthenticationFailed異常
""" val = request.query_params.get('token') if val not in token_list: raise exceptions.AuthenticationFailed("使用者認證失敗") return ('登入使用者', '使用者token') def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ pass class TestPermission(BasePermission): message = "許可權驗證失敗" def has_permission(self, request, view): """ 判斷是否有許可權訪問當前請求 Return `True` if permission is granted, `False` otherwise. :param request: :param view: :return: True有許可權;False無許可權 """ if request.user == "管理員": return True # GenericAPIView中get_object時呼叫 def has_object_permission(self, request, view, obj): """ 檢視繼承GenericAPIView,並在其中使用get_object時獲取物件時,觸發單獨物件許可權驗證 Return `True` if permission is granted, `False` otherwise. :param request: :param view: :param obj: :return: True有許可權;False無許可權 """ if request.user == "管理員": return True class TestView(APIView): # 認證的動作是由request.user觸發 authentication_classes = [TestAuthentication, ] # 許可權 # 迴圈執行所有的許可權 permission_classes = [TestPermission, ] def get(self, request, *args, **kwargs): # self.dispatch print(request.user) print(request.auth) return Response('GET請求,響應內容') def post(self, request, *args, **kwargs): return Response('POST請求,響應內容') def put(self, request, *args, **kwargs): return Response('PUT請求,響應內容')