11 Django RESTful framework 实现缓存
作者:互联网
01-安装
pip install drf-extensions
02-导入
from rest_framework_extensions.cache.mixins import CacheResponseMixin
03-在GoodsListViewSet中添加缓存功能
# CacheResponseMixin一定要放在第一个位置 class GoodsListViewSet(CacheResponseMixin,mixins.ListModelMixin, mixins.RetrieveModelMixin,viewsets.GenericViewSet):
04-设置过期时间,settings里面
# 缓存配置 REST_FRAMEWORK_EXTENSIONS = { 'DEFAULT_CACHE_RESPONSE_TIMEOUT': 5 # 5s过期,时间自己可以随便设定 }
注:这个缓存使用的是内存,每次重启之后就会失效
05-配置redis缓存
pip install django-redis
# settings.py # redis缓存 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } }
06-drf的throttle设置api的访问速率
为了防止爬虫对服务器造成的重大压力,对数据进行访问速率限制就显得非常的重要了 官网使用说明:http://www.django-rest-framework.org/api-guide/throttling/
# settings.py REST_FRAMEWORK = { #限速设置 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', # 未登陆用户 'rest_framework.throttling.UserRateThrottle' # 登陆用户 ), 'DEFAULT_THROTTLE_RATES': { 'anon': '3/minute', # 每分钟可以请求两次 'user': '5/minute' # 每分钟可以请求五次 } }
07-views.py
from rest_framework.throttling import UserRateThrottle,AnonRateThrottle class GoodsListViewSet(CacheResponseMixin,mixins.ListModelMixin, mixins.RetrieveModelMixin,viewsets.GenericViewSet): . . throttle_classes = (UserRateThrottle, AnonRateThrottle)
标签:11,缓存,throttling,mixins,redis,rest,Django,framework 来源: https://www.cnblogs.com/pgxpython/p/10695715.html