Rest_Framework之频率组件部分
生活随笔
收集整理的這篇文章主要介紹了
Rest_Framework之频率组件部分
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、RestFramework之頻率組件源碼部分
頻率組件的源碼部分和權限組件流程一模一樣的,這里就不多說了,直接上源碼的主要邏輯部分:
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():if not throttle.allow_request(request, self):self.throttled(request, throttle.wait())明確表示我們寫的頻率類需要一個allow_request()方法:
頻率類(完成一分鐘同一個ip只能訪問三次):
import time from rest_framework.throttling import BaseThrottleclass MyThrottle(BaseThrottle):visited_record = {}def __init__(self):self.history = Nonedef allow_request(self, request, my_cbv):# 這個my_cbv是源碼中傳的我們的視圖類,這里我們也要傳進去# print(self.get_ident(request)) # 可以獲取本次請求的ipip = request.META.get("REMOTE_ADDR")if ip not in self.visited_record:self.visited_record[ip] = []current_time = time.time()history = self.visited_record[ip]self.history = historywhile history and current_time - history[-1] > 60: # 把與當前訪問時間相差大于60秒的時間都刪掉 history.pop()if len(history) > 2: # 第三次訪問,列表中只有2個值,也滿足條件,大于2個值時不滿足條件return Falsehistory.insert(0, current_time)return Truedef wait(self):"""用于返回還剩多少時間訪問;本次訪問時間:9:50:55[09:50:30, 09:50:20, 09:50:10] 剩余 60 - (9:50:55 - 09:50:10)秒才能訪問:return:"""c_time = time.time()return 60 - (c_time - self.history[-1])視圖類:
class BookView(ModelViewSet):authentication_classes = [UserAuth] #認證類permission_classes = [UserPerm] #權限類throttle_classes = [MyThrottle] #頻率類queryset = Book.objects.all()serializer_class = BookSerializer效果如下:
可以在全局settings配置
REST_FRAMEWORK = {'DEFAULT_PARSER_CLASSES': ('rest_framework.parsers.JSONParser','rest_framework.parsers.FormParser','rest_framework.parsers.MultiPartParser'),'DEFAULT_AUTHENTICATION_CLASSES': 'app01.utils.auth_class.UserAuth',),'DEFAULT_PERMISSION_CLASSES': ('app01.utils.permission_class.VipPermission',),'DEFAULT_THROTTLE_CLASSES': ('app01.utils.throttle_class.MyThrottle',), }?二、使用restframework組件中的提供的訪問限制
實現方式和我們上面的方式基本相同;
基于限制ip的類:SimpleRateThrottle ??
基于ip的訪問限制:
頻率類——局部:
from rest_framework.throttling import SimpleRateThrottleclass MyThrottle(SimpleRateThrottle):rate = '5/m'def get_cache_key(self, request, view): # 這個方法也是必須要有return self.get_ident(request)?
在視圖類中指定頻率類
class BookView(ModelViewSet):throttle_classes = [app_throttles.RateThrottle]queryset = Book.objects.all()serializer_class = BookSerializer?
duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}頻率類——全局:
from rest_framework.throttling import SimpleRateThrottleclass MyThrottle(SimpleRateThrottle):scope = "visit_rate" # 這個值決定了在配置時使用哪個變量描述限制的頻率,必須在settings里面配置def get_cache_key(self, request, view): # 這個方法也是必須要有return self.get_ident(request)這次只能在setttings中配置:
REST_FRAMEWORK = {'DEFAULT_THROTTLE_CLASSES': ('app01.utils.throttle_class.MyThrottle',),"DEFAULT_THROTTLE_RATES": {"visit_rate": "10/m", # 這個參數就是頻率類中定義的那個參數scope, 其中第一個數字10表示10次,后面的m表示一分鐘,還有s,一秒, h, 一小時, d, 一天 } }duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
轉載于:https://www.cnblogs.com/fengchong/p/10100488.html
總結
以上是生活随笔為你收集整理的Rest_Framework之频率组件部分的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 爬虫前期知识的储备(二)
- 下一篇: python网络爬虫基础day01