安装
pip install drf-extensions
引用
from rest_framework_extensions.cache.mixins import CacheResponseMixin
# 加入CacheResponseMixin到第一个入参
class GoodsListViewSet(CacheResponseMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
可以再settings.py中配置有效时间,具体查官方文档
使用redis
pip install django-redis
在settings.py中加入如下
# redis cachae配置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
接口访问评率设置
REST_FRAMEWORK = {
# 加入如下两条
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'anon': '2/minute',
'user': '3/minute'
}
}
views中
from rest_framework.throttling import UserRateThrottle,AnonRateThrottle
class GoodsListViewSet(CacheResponseMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
"""
商品列表页
"""
# 加入此条
throttle_classes = (UserRateThrottle, AnonRateThrottle) # 接口访问频率限制