權限類
主要用途:用戶登錄了,某個介面可能只有超級管理員才能訪問,普通用戶不能訪問
案列:出版社的所有介面,必須登錄,而且是超級管理員才能訪問
分析步驟
第一步:寫一個類,繼承BasePermission
第二步:重寫has_permission方法
第三步:在方法校驗用戶時候有權限(request.user就是當前登錄用戶)
第四步:如果有權限,回傳True,沒有權限,回傳FALSE
第五步:self.message 是給前端的提示資訊
第六步:區域使用,全域使用,區域禁用
model.py
class User(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
user_type = models.IntegerField(default=3, choices=((1, '超級管理員'), (2, '普通用戶'), (3, '2b用戶')))
def __str__(self):
return self.username
permission.py
from rest_framework.permissions import BasePermission
class UserTypePermission(BasePermission):
def has_permission(self, request, view):
# 只有超級管理員有權限
if request.user.user_type == 1:
return True # 有權限
else:
"""
self.message = '普通用戶和2b用戶都沒有權限'
self.message = '您是:%s 用戶,您沒有權限'%request.user.get_user_type_display()
"""
return False # 沒有權限
"""
self.message = '普通用戶和2b用戶都沒有權限'
回傳給前端的提示是什么樣
self.message = '您是:%s 用戶,您沒有權限'%request.user.get_user_type_display()
使用了choice后,user.user_type 拿到的是數字型別,想變成字串 user.get_user_type_display()
"""

view.py
# 匯入我們所寫的那個權限檔案
from .permission import UserTypePermission
# 要驗證必須要登錄,下面的這種方式是區域權限使用
class PublishView(ViewSetMixin, ListCreateAPIView):
# 登錄驗證
authentication_classes = [LoginAuth, ]
# 權限驗證
permission_classes = [UserTypePermission, ]
queryset = Publish.objects.all()
serializer_class = PublishSerializer
class PublishDetailView(ViewSetMixin, RetrieveUpdateDestroyAPIView):
# 登錄驗證
authentication_classes = [LoginAuth, ]
# 權限驗證
permission_classes = [UserTypePermission, ]
queryset = Publish.objects.all()
serializer_class = PublishSerializer
settings.py
全域權限驗證:(要在setting.py檔案中配置)
全域驗證需要注意的是在登錄的時候需要添加區域禁用
permission_classes = []
authentication_classes = []
REST_FRAMEWORK = {
# 'DEFAULT_AUTHENTICATION_CLASSES': ['app01.auth.LoginAuth', ]
'DEFAULT_PERMISSION_CLASSES': ['app01.permission.UserTypePermission', ]
}
# 全域的加上以后區域的就可以注釋掉了
頻率類
認證,權限都通過以后,我們可以限制某個介面的訪問頻率,防止有人惡意攻擊網站,一般根據ip或者用戶限制
自定義頻率類
案例:無論是否登錄和是否有權限,都要限制訪問的頻率,比如一分鐘訪問3次
分析步驟:
第一步:寫一個類:繼承SimpleRateThrottle
第二步:重寫get_cache_key,回傳唯一的字串,會以這個字串做頻率限制
第三步:寫一個類屬性scope=‘隨便寫’,必須要跟組態檔物件
第四步:組態檔中寫
'DEFAULT_THROTTLE_RATES': {
'隨意寫': '3/m' # 3/h 3/s 3/d
}
第五步:區域配置,全域配置,區域禁用
throttling.py(SimpleRateThrottle)
from rest_framework.throttling import BaseThrottle, SimpleRateThrottle
# 我們繼承SimpleRateThrottle去寫,而不是繼承BaseThrottle去寫
class TimeThrottling(SimpleRateThrottle):
# 類屬性,這個類屬性可以隨意命名,但要跟組態檔對應
scope = 'throttling'
def get_cache_key(self, request, view):
"""
# 回傳什么,頻率就以什么做限制
# 可以通過用戶id限制
# 可以通過ip地址限制
"""
return request.META.get('REMOTE_ADDR')
區域配置
class PublishView(ViewSetMixin, ListCreateAPIView):
authentication_classes = [LoginAuth, ]
# permission_classes = [UserTypePermission, ]
# 區域頻率驗證,每分鐘只能訪問五次
throttle_classes = [TimeThrottling, ]
queryset = Publish.objects.all()
serializer_class = PublishSerializer
class PublishDetailView(ViewSetMixin, RetrieveUpdateDestroyAPIView):
authentication_classes = [LoginAuth, ]
# permission_classes = [UserTypePermission, ]
# 區域頻率驗證,每分鐘只能訪問五次
throttle_classes = [TimeThrottling, ]
queryset = Publish.objects.all()
serializer_class = PublishSerializer
全域配置
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': ['app01.throttling.TimeThrottling', ],
'DEFAULT_THROTTLE_RATES': {
'throttling': '5/m' # 一分鐘訪問5次
}
}
內置頻率類
限制未登錄用戶
# 全域使用 限制未登錄用戶1分鐘訪問5次
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '3/m',
}
}
#views.py
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication,BasicAuthentication
class TestView4(APIView):
authentication_classes=[]
permission_classes = []
def get(self,request,*args,**kwargs):
return Response('我是未登錄用戶')
# 區域使用
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication,BasicAuthentication
from rest_framework.throttling import AnonRateThrottle
class TestView5(APIView):
authentication_classes=[]
permission_classes = []
throttle_classes = [AnonRateThrottle]
def get(self,request,*args,**kwargs):
return Response('我是未登錄用戶,TestView5')
限制登錄用戶的訪問頻次
全域:在setting中
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'user': '10/m',
'anon': '5/m',
}
區域配置:
在視圖類中配一個就行
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/518717.html
標籤:其他
