DRF之认证
步骤
- 写一个类,继承
BaseAuthentication - 重写
authenticate方法 - 编写认证类,认证通过后返回两个值
- 认证失败,则抛出异常
APIException或者AuthenticationFailed,会自动捕获并返回
使用
auth.py(自建)
from .models import Tokenfrom rest_framework.exceptions import AuthenticationFailedfrom rest_framework.authentication import BaseAuthenticationclass LoginAuth(BaseAuthentication):def authenticate(self, request):token = request.query_params.get('token')user_token = Token.objects.filter(token=token).first()if user_token:return user_token.user, tokenelse:raise AuthenticationFailed('请先进行登录')
全局认证
settings.py
REST_FRAMEWORK = {# 全局使用认证类'DEFAULT_AUTHENTICATION_CLASSES':['app01.auth.LoginAuth',]}
局部认证
class BookView(APIView):# 在局部视图类添加authentication_classes = [LoginAuth, ]
局部禁用
class BookView(APIView):# 在局部视图类设置为空authentication_classes = []
自定义认证
DRF之权限
步骤
- 写一个类,继承
BasePermission - 重写
has_permission方法 - 在
has_permission中,进行权限的判断,如果有权限,返回True,如果没有权限,返回False,返回的中文提示信息,使用message字段标识
使用
class PermissionAuth(BasePermission):# message = '你不是超级用户,不能访问'def has_permission(self, request, view):# 判断权限,由于权限的执行在认证后执行,到这说明已经认证通过了,认证通过了request.user就是当前登录用户if request.user.user_type == 1:return Trueelse:self.message = '你是%s,无法访问' % request.user.get_user_type_display()return False
全局认证
setting.py
REST_FRAMEWORK = {# 全局使用认证类'DEFAULT_PERMISSION_CLASSES':['app01.auth.PermissionAuth',]}
局部认证
class BookView(APIView):permission_classes = [PermissionAuth,]
局部禁用
class BookView(APIView):permission_classes = []
DRF之频率
步骤
- 写一个类,继承
SimpleRateThrottle - 重写
get_cache_key方法 - 返回什么,就以什么做限制
- 写一个类属性
scope='别名' - 配置文件中配置
REST_FRAMEWORK = {'别名':'3/m'}(s是秒,m是分,h是小时,d是天)
使用
throttling.py
class IPThrottle(SimpleRateThrottle):scope = 'user'def get_cache_key(self, request, view):# return 什么就限制s, 返回ip 返回用户idif request.user.username:return request.META.get('REMOTE_ADDR')
setting.py
REST_FRAMEWORK = {"DEFAULT_THROTTLE_RATES": {# 频率类中scope对应的值'user': '3/m',},}
views.py
class BookView(APIView):throttle_classes = [IPThrottle, ]def get(self, request):return Response('ok')def throttled(self, request, wait):from rest_framework.exceptions import Throttledclass MyThrottled(Throttled):default_detail = '超限限制'extra_detail_singular = '需要等待 {wait} 秒'extra_detail_plural = '需要等待 {wait} 秒'raise MyThrottled(wait)
全局认证
setting.py
REST_FRAMEWORK = {"DEFAULT_THROTTLE_RATES": {# 频率类中scope对应的值'anon':'4/h','user':'5/m'},'DEFAULT_THROTTLE_CLASSES':['app01.throttling.IPThrottle',]}
局部认证
class BookView(ListAPIView):throttle_classes = [MyThrottle, ]
局部禁用
class BookView(APIView):throttle_classes = []
