Skip to content

Commit 9518f0b

Browse files
author
zmrenwu
committed
Step13: 限制接口访问频率
1 parent 66bef88 commit 9518f0b

File tree

3 files changed

+12
-0
lines changed

3 files changed

+12
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,7 @@ $ git clone https://github.com/HelloGitHub-Team/HelloDjango-REST-framework-tutor
201201
12. [基于 drf-haystack 实现文章搜索接口](https://www.zmrenwu.com/courses/django-rest-framework-tutorial/materials/101/))
202202
13. [加缓存为接口提速](https://www.zmrenwu.com/courses/django-rest-framework-tutorial/materials/102/))
203203
14. [API 版本管理](https://www.zmrenwu.com/courses/django-rest-framework-tutorial/materials/103/))
204+
15. [限制接口访问频率](https://www.zmrenwu.com/courses/django-rest-framework-tutorial/materials/104/))
204205

205206
## 公众号
206207
<p align="center">

blog/views.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from rest_framework.permissions import AllowAny
99
from rest_framework.response import Response
1010
from rest_framework.serializers import DateField
11+
from rest_framework.throttling import AnonRateThrottle
1112
from rest_framework_extensions.cache.decorators import cache_response
1213
from rest_framework_extensions.key_constructor.bits import (
1314
ListSqlQueryKeyBit,
@@ -199,9 +200,14 @@ def get_queryset(self):
199200
return Tag.objects.all().order_by("name")
200201

201202

203+
class PostSearchAnonRateThrottle(AnonRateThrottle):
204+
THROTTLE_RATES = {"anon": "5/min"}
205+
206+
202207
class PostSearchView(HaystackViewSet):
203208
index_models = [Post]
204209
serializer_class = PostHaystackSerializer
210+
throttle_classes = [PostSearchAnonRateThrottle]
205211

206212

207213
class ApiVersionTestViewSet(viewsets.ViewSet):

blogproject/settings/common.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,9 @@
144144
# API 版本控制
145145
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.NamespaceVersioning",
146146
"DEFAULT_VERSION": "v1",
147+
# 限流
148+
"DEFAULT_THROTTLE_CLASSES": [
149+
"rest_framework.throttling.AnonRateThrottle",
150+
],
151+
"DEFAULT_THROTTLE_RATES": {"anon": "10/min"},
147152
}

0 commit comments

Comments
 (0)