当前位置:   article > 正文

Django REST framework - 权限和限制

django rest framework 根目录禁止访问

Django REST framework 权限和限制

(你能干什么)

与身份验证和限制一起,权限确定是应该授予还是拒绝访问请求。

在允许任何其他代码继续之前,权限检查始终在视图的最开始运行。权限检查通常使用 request.userrequest.auth 属性中的身份验证信息来确定是否应允许传入请求。

权限用于授予或拒绝不同类别的用户访问API的不同部分。

最简单的权限类型是允许访问任何经过身份验证的用户,并拒绝访问任何未经身份验证的用户。这对应IsAuthenticated于REST框架中的类。

稍微不那么严格的权限样式是允许对经过身份验证的用户进行完全访问,但允许对未经身份验证的用户进行只读访问。这对应IsAuthenticatedOrReadOnly于REST框架中的类。

设置权限的方法

  1. 可以使用该DEFAULT_PERMISSION_CLASSES设置全局设置默认权限策略。例如:

    1. REST_FRAMEWORK = {
    2. 'DEFAULT_PERMISSION_CLASSES': (
    3. 'rest_framework.permissions.IsAuthenticated',
    4. )
    5. }

    如果未指定,则此设置默认允许不受限制的访问:

    1. 'DEFAULT_PERMISSION_CLASSES': (
    2. 'rest_framework.permissions.AllowAny',
    3. )
  2. 您还可以使用APIView基于类的视图在每个视图或每个视图集的基础上设置身份验证策略。

    from rest_framework.permissions import IsAuthenticated
    from rest_framework.response import Response
    from rest_framework.views import APIView

    class ExampleView(APIView):
    permission_classes = (IsAuthenticated,)

    1. def get(self, request, format=None):
    2. content = {
    3. 'status': 'request was permitted'
    4. }
    5. return Response(content)
  3. 或者,使用@api_view具有基于功能的视图的装饰器。

    1. from rest_framework.decorators import api_view, permission_classes
    2. from rest_framework.permissions import IsAuthenticated
    3. from rest_framework.response import Response
    4. @api_view(['GET'])
    5. @permission_classes((IsAuthenticated, ))
    6. def example_view(request, format=None):
    7. content = {
    8. 'status': 'request was permitted'
    9. }
    10. return Response(content)
注意 :当您通过类属性或装饰器设置新的权限类时,您告诉视图忽略settings.py文件中的默认列表集。

如果它们继承自rest_framework.permissions.BasePermission,则可以使用标准Python按位运算符组合权限。例如,IsAuthenticatedOrReadOnly可以写成:

  1. from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS
  2. from rest_framework.response import Response
  3. from rest_framework.views import APIView
  4. class ReadOnly(BasePermission):
  5. def has_permission(self, request, view):
  6. return request.method in SAFE_METHODS
  7. class ExampleView(APIView):
  8. permission_classes = (IsAuthenticated|ReadOnly,)
  9. def get(self, request, format=None):
  10. content = {
  11. 'status': 'request was permitted'
  12. }
  13. return Response(content)

案例

此案例基于 Django REST framework 认证

第一步: 定义一个权限类

"""

自己动手写一个权限组件
"""
from rest_framework.permissions import BasePermission

class MyPermission(BasePermission):

  1. message = '只有VIP才能访问'
  2. def has_permission(self, request, view):
  3. # 认证类中返回了token_obj.user, request_token
  4. # request.auth 等价于request_token
  5. if not request.auth:
  6. return False
  7. # request.user为当前用户对象
  8. if request.user and request.user.type == 1: # 如果是VIP用户
  9. print("requ", request.user, type(request.user))
  10. return True
  11. else:
  12. return False
'
运行

第二步: 使用

视图级别

  1. class CommentViewSet(ModelViewSet):
  2. queryset = models.Comment.objects.all()
  3. serializer_class = app01_serializers.CommentSerializer
  4. authentication_classes = [MyAuth, ]
  5. permission_classes = [MyPermission, ]

全局级别设置

  1. # 在settings.py中设置rest framework相关配置项
  2. REST_FRAMEWORK = {
  3. "DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.MyAuth", ],
  4. "DEFAULT_PERMISSION_CLASSES": ["app01.utils.MyPermission", ]
  5. }

---


限制

(你一分钟能干多少次?)**好像有点污~~ ###

第一步: 自定义限制类

  1. import time
  2. # from rest_framework.throttling import
  3. visit_record = {}
  4. class MyThrottle(object):
  5. def __init__(self):
  6. self.history = None
  7. def allow_request(self, request, view):
  8. # 拿到当前的请求的ip作为访问记录的 key
  9. ip = request.META.get('REMOTE_ADDR')
  10. # 拿到当前请求的时间戳
  11. now = time.time()
  12. if ip not in visit_record:
  13. visit_record[ip] = []
  14. # 把当前请求的访问记录拿出来保存到一个变量中
  15. history = visit_record[ip]
  16. self.history = history
  17. # 循环访问历史,把超过10秒钟的请求时间去掉
  18. while history and now - history[-1] > 10:
  19. history.pop()
  20. # 此时 history中只保存了最近10秒钟的访问记录
  21. if len(history) >= 3:
  22. return False
  23. else:
  24. # 判断之前有没有访问记录(第一次来)
  25. self.history.insert(0, now)
  26. return True
  27. def wait(self):
  28. """告诉客户端还需等待多久"""
  29. now = time.time()
  30. return self.history[-1] + 10 - now
  31. # history = ['9:56:12', '9:56:10', '9:56:09', '9:56:08'] # '9:56:18' - '9:56:12'
  32. # history = ['9:56:19', '9:56:18', '9:56:17', '9:56:08']
  33. # 最后一项到期的时间就是下一次允许请求的时间
  34. # 最后一项到期的时间:now - history[-1] > 10
  35. # 最后一项还剩多少时间过期
  36. # history[-1] + 10 - now

第二步: 使用

视图中使用
  1. class CommentViewSet(ModelViewSet):
  2. queryset = models.Comment.objects.all()
  3. serializer_class = app01_serializers.CommentSerializer
  4. throttle_classes = [MyThrottle, ]
全局中使用
  1. # 在settings.py中设置rest framework相关配置项
  2. REST_FRAMEWORK = {
  3. "DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.MyAuth", ],
  4. "DEFAULT_PERMISSION_CLASSES": ["app01.utils.MyPermission", ]
  5. "DEFAULT_THROTTLE_CLASSES": ["app01.utils.MyThrottle", ]
  6. }

嫌麻烦的话,还可以使用内置限制类,哈哈~

  1. from rest_framework.throttling import SimpleRateThrottle
  2. class VisitThrottle(SimpleRateThrottle):
  3. scope = "xxx"
  4. def get_cache_key(self, request, view):
  5. return self.get_ident(request)
全局配置
  1. # 在settings.py中设置rest framework相关配置项
  2. REST_FRAMEWORK = {
  3. "DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.MyAuth", ],
  4. # "DEFAULT_PERMISSION_CLASSES": ["app01.utils.MyPermission", ]
  5. "DEFAULT_THROTTLE_CLASSES": ["app01.utils.VisitThrottle", ],
  6. "DEFAULT_THROTTLE_RATES": {
  7. "xxx": "5/m",
  8. }
  9. }

转载于:https://www.cnblogs.com/konghui/p/10351911.html

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号