Django-cache缓存
概述:
对于中等流量的网站来说,尽可能减少开销是必要的,缓存数据就是为了保存哪些需要很多计算资源的结果,这样就不必在下次请求消耗计算机资源 Django自带一个非常健壮的缓存功能
(1)缓存配置
settings.py
配置缓存在数据库中
CACHES={
'default':{
#缓存位置
'BACKEND':'django.core.cache.backend.db.DatabaseCache',
# 缓存的表名称
'LOCATION':'my_cache_table',
'OPTIONS':{
# 缓存的最多数据条数
'MAX_ENTRIES':'10'
},
#缓存前缀
'KEY_PREFIX':'cache',
}
}
(2)创建缓存表
python manage.py createchachetable my_cache_table
(3)缓存的使用
导入缓存
from Django.views.decorations.cache import cache_page
使用:
@cache_page()
+ time缓存时间,单位秒
+ cache 缓存配置 默认使用default
+ key_prefix 前置字符串
from django.views.decorators.cache import cache_page
# Create your views here.
@cache_page(10)
def index(req):
print('你看到我了吗?')
u = User.objects.all()
return render(req,'show_data.html',{'data':u})
手动设置缓存
通过装饰器设置缓存,设置 了缓存,不再执行视图函数代码,而是将数据库或者缓存的内容取出
直接响应,坚强了数据库服务器的压力和视图函数代码执行的时间,提高了用户体验度和减轻压力
#缓存操作
#设置缓存
cache.set(key,value,timeout)
set_many
#获取
cache.get(key)
get_many
#删除:
cache.delete(key)
delete_many
#清空:
cache.clear()
实例:
from django.core.cache import cache
from django.template import loader
# 手动设置缓存
def index(req):
# 获取key为user_cache的缓存数据
user_cache = cache.get('user_cache')
# 判断是否存在缓存
if not user_cache:
u = User.objects.all()
tem = loader.get_template('show_data.html')
user_cache = tem.render({'data':u})
cache.set('user_cache',user_cache,20)
print('没缓存...')
return HttpResponse(user_cache)
使用redis作为缓存
安装:
pip install django-redis
配置:
settings.py
# 配置缓存在redis中
CACHES = {
'default':{
'BACKEND':'django_redis.cache.RedisCache',
'LOCATION':'redis://127.0.0.1:6379/1'
}
}
四,文件系统缓存
配置settings.py
实例:
CACHES = {
'default':{
'BACKEND':'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION':'/home/xlg/桌面/my_cache',
}
}
## 五、本地内存缓存
**配置settings.py**
```python
CACHES = {
'default':{
'BACKEND':'django.core.cache.backends.locmem.LocMemCache',
# 'LOCATION':'unique-snowflake',
}
}
如果值设置一个本地缓存 则不需给LOCATION值 如果有多个的话 需要最少设置一个用来区分