权限类与频率类

打印 上一主题 下一主题

主题 894|帖子 894|积分 2682

权限类

主要用途:用户登录了,某个接口可能只有超级管理员才能访问,普通用户不能访问
案列:出版社的所有接口,必须登录,而且是超级管理员才能访问
分析步骤
  1. 第一步:写一个类,继承BasePermission
  2. 第二步:重写has_permission方法
  3. 第三步:在方法校验用户时候有权限(request.user就是当前登录用户)
  4. 第四步:如果有权限,返回True,没有权限,返回FALSE
  5. 第五步:self.message 是给前端的提示信息
  6. 第六步:局部使用,全局使用,局部禁用
复制代码
model.py
  1. class User(models.Model):
  2.     username = models.CharField(max_length=32)
  3.     password = models.CharField(max_length=32)
  4.     user_type = models.IntegerField(default=3, choices=((1, '超级管理员'), (2, '普通用户'), (3, '2b用户')))
  5.     def __str__(self):
  6.         return self.username
复制代码
permission.py
  1. from rest_framework.permissions import BasePermission
  2. class UserTypePermission(BasePermission):
  3.     def has_permission(self, request, view):
  4.         # 只有超级管理员有权限
  5.         if request.user.user_type == 1:
  6.             return True  # 有权限
  7.         else:
  8.             """
  9.             self.message = '普通用户和2b用户都没有权限'
  10.             self.message = '您是:%s 用户,您没有权限'%request.user.get_user_type_display()
  11.             """
  12.             return False  # 没有权限
  13. """
  14. self.message = '普通用户和2b用户都没有权限'
  15.     返回给前端的提示是什么样
  16. self.message = '您是:%s 用户,您没有权限'%request.user.get_user_type_display()
  17.     使用了choice后,user.user_type 拿到的是数字类型,想变成字符串 user.get_user_type_display()
  18. """
复制代码

view.py
  1. # 导入我们所写的那个权限文件
  2. from .permission import UserTypePermission
  3. # 要验证必须要登录,下面的这种方式是局部权限使用
  4. class PublishView(ViewSetMixin, ListCreateAPIView):
  5.     # 登录验证
  6.     authentication_classes = [LoginAuth, ]
  7.     # 权限验证
  8.     permission_classes = [UserTypePermission, ]
  9.     queryset = Publish.objects.all()
  10.     serializer_class = PublishSerializer
  11. class PublishDetailView(ViewSetMixin, RetrieveUpdateDestroyAPIView):
  12.     # 登录验证
  13.     authentication_classes = [LoginAuth, ]
  14.     # 权限验证
  15.     permission_classes = [UserTypePermission, ]
  16.     queryset = Publish.objects.all()
  17.     serializer_class = PublishSerializer
复制代码
settings.py
  1. 全局权限验证:(要在setting.py文件中配置)
  2. 全局验证需要注意的是在登录的时候需要添加局部禁用
  3.     permission_classes = []
  4.     authentication_classes = []
  5. REST_FRAMEWORK = {
  6.     # 'DEFAULT_AUTHENTICATION_CLASSES': ['app01.auth.LoginAuth', ]
  7.     'DEFAULT_PERMISSION_CLASSES': ['app01.permission.UserTypePermission', ]
  8. }
  9. # 全局的加上以后局部的就可以注释掉了
复制代码
频率类

认证,权限都通过以后,我们可以限制某个接口的访问频率,防止有人恶意攻击网站,一般根据ip或者用户限制
自定义频率类

案例:无论是否登录和是否有权限,都要限制访问的频率,比如一分钟访问3次
分析步骤:
  1. 第一步:写一个类:继承SimpleRateThrottle
  2. 第二步:重写get_cache_key,返回唯一的字符串,会以这个字符串做频率限制
  3. 第三步:写一个类属性scope=‘随便写’,必须要跟配置文件对象
  4. 第四步:配置文件中写
  5.     'DEFAULT_THROTTLE_RATES': {
  6.         '随意写': '3/m'  # 3/h  3/s  3/d
  7.         }
  8. 第五步:局部配置,全局配置,局部禁用
复制代码
throttling.py(SimpleRateThrottle)
  1. from rest_framework.throttling import BaseThrottle, SimpleRateThrottle
  2. # 我们继承SimpleRateThrottle去写,而不是继承BaseThrottle去写
  3. class TimeThrottling(SimpleRateThrottle):
  4.     # 类属性,这个类属性可以随意命名,但要跟配置文件对应
  5.     scope = 'throttling'
  6.    
  7.     def get_cache_key(self, request, view):
  8.         """
  9.         # 返回什么,频率就以什么做限制
  10.         # 可以通过用户id限制
  11.         # 可以通过ip地址限制
  12.         """
  13.         return request.META.get('REMOTE_ADDR')
复制代码
局部配置
  1. class PublishView(ViewSetMixin, ListCreateAPIView):
  2.     authentication_classes = [LoginAuth, ]
  3.     # permission_classes = [UserTypePermission, ]
  4.     # 局部频率验证,每分钟只能访问五次
  5.     throttle_classes = [TimeThrottling, ]
  6.     queryset = Publish.objects.all()
  7.     serializer_class = PublishSerializer
  8. class PublishDetailView(ViewSetMixin, RetrieveUpdateDestroyAPIView):
  9.     authentication_classes = [LoginAuth, ]
  10.     # permission_classes = [UserTypePermission, ]
  11.     # 局部频率验证,每分钟只能访问五次
  12.     throttle_classes = [TimeThrottling, ]
  13.     queryset = Publish.objects.all()
  14.     serializer_class = PublishSerializer
复制代码
全局配置
  1. REST_FRAMEWORK = {
  2.     'DEFAULT_THROTTLE_CLASSES': ['app01.throttling.TimeThrottling', ],
  3.     'DEFAULT_THROTTLE_RATES': {
  4.         'throttling': '5/m'  # 一分钟访问5次
  5.     }
  6. }
复制代码
内置频率类

限制未登录用户
  1. # 全局使用  限制未登录用户1分钟访问5次
  2. REST_FRAMEWORK = {
  3.     'DEFAULT_THROTTLE_CLASSES': (
  4.         'rest_framework.throttling.AnonRateThrottle',
  5.     ),
  6.     'DEFAULT_THROTTLE_RATES': {
  7.         'anon': '3/m',
  8.     }
  9. }
  10. #views.py
  11. from rest_framework.permissions import IsAdminUser
  12. from rest_framework.authentication import SessionAuthentication,BasicAuthentication
  13. class TestView4(APIView):
  14.     authentication_classes=[]
  15.     permission_classes = []
  16.     def get(self,request,*args,**kwargs):
  17.         return Response('我是未登录用户')
  18. # 局部使用
  19. from rest_framework.permissions import IsAdminUser
  20. from rest_framework.authentication import SessionAuthentication,BasicAuthentication
  21. from rest_framework.throttling import AnonRateThrottle
  22. class TestView5(APIView):
  23.     authentication_classes=[]
  24.     permission_classes = []
  25.     throttle_classes = [AnonRateThrottle]
  26.     def get(self,request,*args,**kwargs):
  27.         return Response('我是未登录用户,TestView5')
复制代码
限制登录用户的访问频次
  1. 全局:在setting中
  2.   'DEFAULT_THROTTLE_CLASSES': (
  3.         'rest_framework.throttling.AnonRateThrottle',
  4.         'rest_framework.throttling.UserRateThrottle'
  5.     ),
  6.     'DEFAULT_THROTTLE_RATES': {
  7.         'user': '10/m',
  8.         'anon': '5/m',
  9.     }
  10.         
  11. 局部配置:
  12.         在视图类中配一个就行
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

王海鱼

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表