DRF 三大认证
认证类:登陆认证
authentication.py
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from .models import Usertaken
class LoginAuth(BaseAuthentication):
def authenticate(self, request):
taken = request.META.get('HTTP_TOKEN')
token=Usertaken.objects.filter(taken=taken).first()
if token:
user = token.user
return (user, taken)
else:
raise AuthenticationFailed('很抱歉,您没有登陆,不能操作')
- 全局使用
settings.py
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.LoginAuth",]
}
- 局部使用
views.py
#局部使用,只需要在视图类里加入:
authentication_classes = [LoginAuth, ]
权限类:用户权限
permissions.py
from rest_framework.permissions import BasePermission
class UserPermission(BasePermission):
def has_permission(self, request, view):
print(request.user.user_type)
if request.user.user_type==3:
return True
else:
user_type = request.user.get_user_type_display()
self.message = f'您是:{user_type},您没有权限访问'
return False
- 全局使用
settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'app01.permissions.UserPermission'
],
}
- 局部使用
views.py
permission_classes = [UserPermission]
-
内置权限类
-
AllowAny 允许所有用户
-
IsAuthenticated 仅通过认证的用户
-
IsAdminUser 仅管理员用户
-
IsAuthenticatedOrReadOnly 已经登陆认证的用户可以对数据进行增删改操作,没有登陆认证的只能查看数据。
-
频率类:频率限制
throttling.py
from rest_framework.throttling import SimpleRateThrottle
class CommonThrottle(SimpleRateThrottle):
rate = '3/m' # 一分钟3次
def get_cache_key(self, request, view):
# 返回什么,就会以什么做限制--》ip地址限制;用户id
return request.META.get('REMOTE_ADDR')
- 全局使用
settings.py
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': ['app01.throttling.CommonThrottle'],
}
- 局部使用
views.py
throttle_classes = [CommonThrottle]
- 继承
BaseThrottle
实现频率限制
from django.core.cache import cache as default_cache
from rest_framework.throttling import BaseThrottle
from rest_framework.exceptions import AuthenticationFailed
import time, copy
class UpdateBaseThrottle(BaseThrottle):
cache = default_cache
def __init__(self):
self.rate='3/m'
self.num, self.duration = self.parse_rate(self.rate)
def parse_rate(self, rate):
if rate is None:
return (None, None)
num, period = rate.split('/')
num = int(num)
duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
return num, duration
def allow_request(self, request, view):
self.id = request.META.get('REMOTE_ADDR')
self.history = self.cache.get(self.id, [])
if len(self.history) >= self.num:
blank = time.time() - self.history[0]
if blank > self.duration:
self.history.pop(0)
return self.throttle_success()
else:
raise AuthenticationFailed(f'达到访问次数,还需等待{self.duration-blank}s')
else:
return self.throttle_success()
def throttle_success(self):
self.history.append(time.time())
self.cache.set(self.id, copy.copy(self.history))
return True