rest-framework頻率組件

來源:互聯網
上載者:User

標籤:generics   nbsp   rmi   res   add   text   not   ice   visit   

throttle(訪問頻率)組件1.局部視圖throttle
from rest_framework.throttling import BaseThrottleVISIT_RECORD={}class VisitThrottle(BaseThrottle):    def __init__(self):        self.history=None    def allow_request(self,request,view):        remote_addr = request.META.get(‘REMOTE_ADDR‘)        print(remote_addr)        import time        ctime=time.time()        if remote_addr not in VISIT_RECORD:            VISIT_RECORD[remote_addr]=[ctime,]            return True        history=VISIT_RECORD.get(remote_addr)        self.history=history        while history and history[-1]<ctime-60:            history.pop()        if len(history)<3:            history.insert(0,ctime)            return True        else:            return False    def wait(self):        import time        ctime=time.time()        return 60-(ctime-self.history[-1])

在views.py中:

from app01.service.throttles import *class BookViewSet(generics.ListCreateAPIView):    throttle_classes = [VisitThrottle,]    queryset = Book.objects.all()    serializer_class = BookSerializers

全域頻率設定:

REST_FRAMEWORK={    "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],    "DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",],    "DEFAULT_THROTTLE_CLASSES":["app01.service.throttles.VisitThrottle",]}
內建throttle類:

在app01.service.throttles.py修改為:

class VisitThrottle(SimpleRateThrottle):    scope="visit_rate"    def get_cache_key(self, request, view):        return self.get_ident(request)

最後在settings中配置:

REST_FRAMEWORK={    "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],    "DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",],    "DEFAULT_THROTTLE_CLASSES":["app01.service.throttles.VisitThrottle",],    "DEFAULT_THROTTLE_RATES":{        "visit_rate":"5/m",    }}

 

rest-framework頻率組件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.