還是通過源碼進行查看
dispatch
-----> self.initial(request, *args, **kwargs)
-----> 查看initial方法
----> self.check_permissions(request)
----> 查看check_permission()方法
---->
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():
if not permission.has_permission(request, self):
self.permission_denied(
request, message=getattr(permission, 'message', None)
)
和之前的用戶認證一毛一樣木张,這個靜態(tài)列表可以局部配置代芜,也可以全局配置环凿,調(diào)用了權(quán)限認證類的has_permission方法呵曹,然后返回了權(quán)限類中的屬性message反射的方式
寸五。
- 我們在utils包中創(chuàng)建權(quán)限認證類啡专,重寫has_permission方法冲杀,定義message靜態(tài)字段怜俐,函數(shù)返回true或者false身堡。
- 然后看怎么在全局中配置,也就是找到他的鍵拍鲤,查看
get_permission
,找到了permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
,所以我們在settings中定義的REST_FRAMEWORK中贴谎,添加新的鍵值對,鍵為DEFAULT_PERMISSION_CLASSES
,值為utils包中權(quán)限認證類的路徑季稳。
權(quán)限認證類也有內(nèi)置的類擅这,
from restframework.permissions import Basepermission
,自定義的權(quán)限認證類繼承這個類。
代碼實現(xiàn)
utils.permission.py.Mypermission 權(quán)限類
from rest_framework.permissions import BasePermission
class Mypermission(BasePermission):
'''用戶權(quán)限類'''
def has_permission(self, request, view):
if request.user.user_type != 'SVIP': # 具體權(quán)限邏輯
return False
return True
views.py 視圖函數(shù)
from utils.permission import Mypermission
class OrderView(APIView):
# authentication_classes = [Authentication,] # 局部引用
permission_classes = [Mypermission,]
def get(self,request):
ret = {'code':10000,'msg':None}
try:
pass # 具體視圖函數(shù)邏輯
except Exception as e:
pass # 拋出異常
return JsonResponse(ret)
settings全局使用
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES':['app1.utils.permission.Myspermission'],
}