Django Restful Framework【第三篇】认证、权限、限制访问频率

一、认证

认证请求头

views.py

  

自定义认证功能

 

 

二、权限

1、需求:Host是匿名用户和用户都能访问  #匿名用户的request.user = none;User只有注册用户能访问

urls.py

  

views.py

  

认证和权限配合使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class SalaryView(APIView):
    '''用户能访问'''
    message ='无权访问'
    authentication_classes = [MyAuthentication,]  #验证是不是用户
    permission_classes = [MyPermission,AdminPermission,] #再看用户有没有权限,如果有权限在判断有没有管理员的权限
    def get(self,request):
        return Response('薪资列表')
 
    def permission_denied(self, request, message=None):
        """
        If request is not permitted, determine what kind of exception to raise.
        """
        if request.authenticators and not request.successful_authenticator:
            '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了'''
            raise exceptions.NotAuthenticated(detail='无权访问')
        raise exceptions.PermissionDenied(detail=message)

  

如果遇上这样的,还可以自定制,参考源码

复制代码
    def check_permissions(self, request):
        """
        Check if the request should be permitted.
        Raises an appropriate exception if the request is not permitted.
        """
        for permission in self.get_permissions():
            #循环每一个permission对象,调用has_permission
            #如果False,则抛出异常
            #True 说明有权访问
            if not permission.has_permission(request, self):
                self.permission_denied(
                    request, message=getattr(permission, 'message', None)
                )
复制代码
    def permission_denied(self, request, message=None):
        """
        If request is not permitted, determine what kind of exception to raise.
        """
        if request.authenticators and not request.successful_authenticator:
            '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了'''
            raise exceptions.NotAuthenticated()
        raise exceptions.PermissionDenied(detail=message)

那么我们可以重写permission_denied这个方法,如下:

views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class UsersView(APIView):
    '''用户能访问,request.user里面有值'''
    authentication_classes = [MyAuthentication,]
    permission_classes = [MyPermission,]
    def get(self,request):
        return Response('用户列表')
 
    def permission_denied(self, request, message=None):
        """
        If request is not permitted, determine what kind of exception to raise.
        """
        if request.authenticators and not request.successful_authenticator:
            '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了'''
            raise exceptions.NotAuthenticated(detail='无权访问')
        raise exceptions.PermissionDenied(detail=message)

  

2. 全局使用

上述操作中均是对单独视图进行特殊配置,如果想要对全局进行配置,则需要再配置文件中写入即可。

settings.py

  

Views.py

  

 

三、限流

1、为什么要限流呢?  

答:防爬

2、限制访问频率源码分析

self.check_throttles(request)
1
self.check_throttles(request)
check_throttles
1
2
3
4
5
6
7
8
9
10
11
12
13
def check_throttles(self, request):
        """
        Check if request should be throttled.
        Raises an appropriate exception if the request is throttled.
        """
        for throttle in self.get_throttles():
            #循环每一个throttle对象,执行allow_request方法
            # allow_request:
                #返回False,说明限制访问频率
                #返回True,说明不限制,通行
            if not throttle.allow_request(request, self):
                self.throttled(request, throttle.wait())
                #throttle.wait()表示还要等多少秒就能访问了
get_throttles
1
2
3
4
5
6
def get_throttles(self):
        """
        Instantiates and returns the list of throttles that this view uses.
        """
        #返回对象
        return [throttle() for throttle in self.throttle_classes]
找到类,可自定制类throttle_classes
1
throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
BaseThrottle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class BaseThrottle(object):
    """
    Rate throttling of requests.
    """
 
    def allow_request(self, request, view):
        """
        Return `True` if the request should be allowed, `False` otherwise.
        """
        raise NotImplementedError('.allow_request() must be overridden')
 
    def get_ident(self, request):
        """
        Identify the machine making the request by parsing HTTP_X_FORWARDED_FOR
        if present and number of proxies is > 0. If not use all of
        HTTP_X_FORWARDED_FOR if it is available, if not use REMOTE_ADDR.
        """
        xff = request.META.get('HTTP_X_FORWARDED_FOR')
        remote_addr = request.META.get('REMOTE_ADDR')
        num_proxies = api_settings.NUM_PROXIES
 
        if num_proxies is not None:
            if num_proxies == 0 or xff is None:
                return remote_addr
            addrs = xff.split(',')
            client_addr = addrs[-min(num_proxies, len(addrs))]
            return client_addr.strip()
 
        return ''.join(xff.split()) if xff else remote_addr
 
    def wait(self):
        """
        Optionally, return a recommended number of seconds to wait before
        the next request.
        """
        return None
也可以重写allow_request方法
 
可自定制返回的错误信息throttled
1
2
3
4
5
def throttled(self, request, wait):
        """
        If request is throttled, determine what kind of exception to raise.
        """
        raise exceptions.Throttled(wait)
raise exceptions.Throttled(wait)错误信息详情
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Throttled(APIException):
    status_code = status.HTTP_429_TOO_MANY_REQUESTS
    default_detail = _('Request was throttled.')
    extra_detail_singular = 'Expected available in {wait} second.'
    extra_detail_plural = 'Expected available in {wait} seconds.'
    default_code = 'throttled'
 
    def __init__(self, wait=None, detail=None, code=None):
        if detail is None:
            detail = force_text(self.default_detail)
        if wait is not None:
            wait = math.ceil(wait)
            detail = ' '.join((
                detail,
                force_text(ungettext(self.extra_detail_singular.format(wait=wait),
                                     self.extra_detail_plural.format(wait=wait),
                                     wait))))
        self.wait = wait
        super(Throttled, self).__init__(detail, code)

  

 下面来看看最简单的从源码中分析的示例,这只是举例说明了一下

urls.py
1
2
3
4
5
6
from django.conf.urls import url
from app04 import views
urlpatterns = [
    url('limit/',views.LimitView.as_view()),
 
]
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import exceptions
# from rest_framewor import
# Create your views here.
class MyThrottle(object):
    def allow_request(self,request,view):
        #返回False,限制
        #返回True,不限制
        pass
    def wait(self):
        return 1000
 
 
class LimitView(APIView):
    authentication_classes = []  #不让认证用户
    permission_classes = []  #不让验证权限
    throttle_classes = [MyThrottle, ]
    def get(self,request):
        # self.dispatch
        return Response('控制访问频率示例')
 
    def throttled(self, request, wait):
        '''可定制方法设置中文错误'''
        # raise exceptions.Throttled(wait)
        class MyThrottle(exceptions.Throttled):
            default_detail = '请求被限制'
            extra_detail_singular = 'Expected available in {wait} second.'
            extra_detail_plural = 'Expected available in {wait} seconds.'
            default_code = '还需要再等{wait}秒'
        raise MyThrottle(wait)

  

3、需求:对匿名用户进行限制,每个用户一分钟允许访问10次(只针对用户来说)

a、基于用户IP限制访问频率

流程分析:

  • 先获取用户信息,如果是匿名用户,获取IP。如果不是匿名用户就可以获取用户名。
  • 获取匿名用户IP,在request里面获取,比如IP= 1.1.1.1。
  • 吧获取到的IP添加到到recode字典里面,需要在添加之前先限制一下。
  • 如果时间间隔大于60秒,说明时间久远了,就把那个时间给剔除 了pop。在timelist列表里面现在留的是有效的访问时间段。
  • 然后判断他的访问次数超过了10次没有,如果超过了时间就return False。
  • 美中不足的是时间是固定的,我们改变他为动态的:列表里面最开始进来的时间和当前的时间进行比较,看需要等多久。

具体实现:

views初级版本
 
稍微做了改动

  

 

b、用resetframework内部的限制访问频率(利于Django缓存)

 源码分析:

from rest_framework.throttling import BaseThrottle,SimpleRateThrottle  #限制访问频率
BaseThrottle相当于一个抽象类

 

SimpleRateThrottle

  

请求一进来会先执行SimpleRateThrottle这个类的构造方法

__init__

  

get_rate

  

parse_rate

  

allow_request

  

wait

  

代码实现:

views.py

  

记得在settings里面配置

settings.py

  

4、对匿名用户进行限制,每个用户1分钟允许访问5次,对于登录的普通用户1分钟访问10次,VIP用户一分钟访问20次

  • 比如首页可以匿名访问
  • #先认证,只有认证了才知道是不是匿名的,
  • #权限登录成功之后才能访问, ,index页面就不需要权限了
  • If request.user  #判断登录了没有
urls.py
views.py

 

四、总结

1、认证:就是检查用户是否存在;如果存在返回(request.user,request.auth);不存在request.user/request.auth=None

 2、权限:进行职责的划分

3、限制访问频率

复制代码
认证
    - 类:authenticate/authenticate_header ##验证不成功的时候执行的
    - 返回值:
        - return None,
        - return (user,auth),
        - raise 异常
    - 配置:
        - 视图:
            class IndexView(APIView):
                authentication_classes = [MyAuthentication,]
        - 全局:
            REST_FRAMEWORK = {
                    'UNAUTHENTICATED_USER': None,
                    'UNAUTHENTICATED_TOKEN': None,
                    "DEFAULT_AUTHENTICATION_CLASSES": [
                        # "app02.utils.MyAuthentication",
                    ],
            }

权限 
    - 类:has_permission/has_object_permission
    - 返回值: 
        - True、#有权限
        - False、#无权限
        - exceptions.PermissionDenied(detail="错误信息")  #异常自己随意,想抛就抛,错误信息自己指定
    - 配置:
        - 视图:
            class IndexView(APIView):
                permission_classes = [MyPermission,]
        - 全局:
            REST_FRAMEWORK = {
                    "DEFAULT_PERMISSION_CLASSES": [
                        # "app02.utils.MyAuthentication",
                    ],
            }
限流
    - 类:allow_request/wait PS: scope = "wdp_user"
    - 返回值:
      return True、#不限制
      return False #限制 - 配置: - 视图: class IndexView(APIView): throttle_classes=[AnonThrottle,UserThrottle,] def get(self,request,*args,**kwargs): self.dispatch return Response('访问首页') - 全局 REST_FRAMEWORK = { "DEFAULT_THROTTLE_CLASSES":[ ], 'DEFAULT_THROTTLE_RATES':{ 'wdp_anon':'5/minute', 'wdp_user':'10/minute', } }
复制代码

 

posted @   小河马的博客  阅读(1377)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示