django cache 缓存
1.缓存可以解决代码大量的重复请求,减少访问者对数据库的压力
官网:https://docs.djangoproject.com/zh-hans/2.2/topics/cache/
2缓存的工作原理:
given a URL, try finding that page in the cache
if the page is in the cache:
return the cached page
else:
generate the page
save the generated page in the cache (for next time)
return the generated page
3.缓存位置支持以下几种:
Memcached,数据库缓存,文件系统缓存,本地内存缓存,虚拟缓存(用于开发模式),使用自定义的缓存后台
其中Memchahed速度是最快的,应为是基于内存的
4.缓存的方式有以下几种:
1.视图缓存
from django.views.decorators.cache import cache_page
#在函数前面加装饰器
@cache_page(60 * 15)
def my_view(request):
...
2.模板片段缓存
{% load cache %}
{% cache 500 sidebar %}
.. sidebar ..
{% endcache %}
直接缓存的代码加上以上代码
3.低级缓存API
只缓存部分信息
5.cache基本用法: