缓存
背景介绍:
动态网站的问题就在于它是动态的。 也就是说每次用户访问一个页面,服务器要执行数据库查询,启动模板,执行业务逻辑以及最终生成一个你所看到的网页,这一切都是动态即时生成的。 从处理器资源的角度来看,这是比较昂贵的。
缓存的目的是为了避免重复计算,特别是对一些比较耗时间、资源的计算。 下面的伪代码演示了如何对动态页面的结果进行缓存。
django 自带的缓存:
内存缓存、数据库缓存、文件系统缓存、本地内存缓存、仿缓存,自定义后端缓存,本篇介绍redis+drf-extensions实现缓存
环境配置:
$ pip install django-redis $ pip install drf-extensions
settings.py
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PASSWORD": "mysecret" } } }
views.py(装饰器更灵活)
from rest_framework_extensions.cache.decorators import ( cache_response ) class GoodsView(APIView): @cache_response(timeout=60*60, cache='default') def get(self,request,*args,**kwargs): ... # or @cache_response(timeout=60*60, cache='default') def list(self,request,*args,**kwargs): ......
- timeout 缓存时间
- cache 缓存使用的Django缓存后端(即CACHES配置中的键名称)
限制爬虫
restframework 自带 Throttling,也是利用了cache,统计ip,user请求次数
settings.py
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '3/min', 'user': '5/min' } } """ ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day') """
views.py
throttle_classes = (UserRateThrottle, AnonRateThrottle) # 对象级 def get_throttles(self): # ... return super().get_throttles()
源码详见APIView