view–指定评率类 throttle_classes = (UserRateThrottle, AnonRateThrottle)
from rest_framework
.throttling
import UserRateThrottle
, AnonRateThrottle
class GoodsListViewSet(CacheResponseMixin
, mixins
.ListModelMixin
, mixins
.RetrieveModelMixin
, viewsets
.GenericViewSet
):
"""
商品列表页, 分页, 搜索, 过滤, 排序
"""
throttle_classes
= (UserRateThrottle
, AnonRateThrottle
)
queryset
= Goods
.objects
.all()
serializer_class
= GoodsSerializer
pagination_class
= GoodsPagination
filter_backends
= [DjangoFilterBackend
, filters
.SearchFilter
, filters
.OrderingFilter
]
filter_class
= GoodsFilter
search_fields
= ['name', 'goods_brief', "goods_desc"]
ordering_fields
= ["sold_num", "shop_price"]
def retrieve(self
, request
, *args
, **kwargs
):
instance
= self
.get_object
()
instance
.click_num
+= 1
instance
.save
()
serializer
= self
.get_serializer
(instance
)
return Response
(serializer
.data
)
settings
REST_FRAMEWORK
= {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '60/minute',
'user': '60/minute'
}
}
效果图 官方 官方文档:https://www.django-rest-framework.org/api-guide/throttling/