首先,网上看了很多访问频率限制的教程,都是针对Django REST Framework(DRF)的使用的throttle,对于普通的Django项目做访问频率限制的很少,所以有了这篇文章。
使用前请先安装 django-throttle-requests模块
pip install -i https://pypi.douban.com/simple django-throttle-requests
一、先在Django项目的settings.py文件中定义访问频率限制的规则
THROTTLE_ZONES = {
# 限制请求频率 10次/分
'default': {
'VARY':'throttle.zones.RemoteIP',
'NUM_BUCKETS':2, # Number of buckets worth of history to keep. Must be at least 2
'BUCKET_INTERVAL':1 * 60, # Period of time to enforce limits.
'BUCKET_CAPACITY':10, # Maximum number of requests allowed within BUCKET_INTERVAL
},
# 限制请求频率 50次/小时
'order': {
'VARY':'throttle.zones.RemoteIP',
'NUM_BUCKETS':2, # Number of buckets worth of history to keep. Must be at least 2
'BUCKET_INTERVAL':60 * 60, # Period of time to enforce limits.
'BUCKET_CAPACITY':50, # Maximum number of requests allowed within BUCKET_INTERVAL
},
}
THROTTLE_BACKEND = 'throttle.backends.cache.CacheBackend'
# Force throttling when DEBUG=True
THROTTLE_ENABLED = True
二、在视图views.py文件中使用,既可以对FBV(函数视图)使用也可以用在CBV(类视图)上
views.py
from django.views import View
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from throttle.decorators import throttle
from .models import Blog
# 在普通FBV上使用,指定default
@throttle(zone='default')
def bloginfo(request):
blog = Blog.objects.get(pk=1)
return JsonResponse({"name": blog.name}, )
class BlogView(View):
# 装饰在CBV内部的get方法上
@method_decorator(throttle(zone='default'))
def get(self, request):
blog = Blog.objects.get(pk=1)
return JsonResponse({"name": blog.name})
# 装饰在CBV的类上,用name指定对哪个方法使用throttle
@method_decorator(throttle(zone='default'), name='get')
class BlogView2(View):
def get(self, request):
blog = Blog.objects.get(pk=1)
return JsonResponse({"name": blog.name})
def post(self, request):
return JsonResponse({"name": 'name'})
urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('bloginfo/', views.bloginfo),
path('blogview/', views.BlogView.as_view()),
path('blogview2/', views.BlogView2.as_view()),
]
正常访问
当超过限制访问的频率时就会返回403
pycharm输出