django的cache

使用文件缓存

#settings.py
 
CACHES = {
 
'default': {
 
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
 
'LOCATION': '/var/tmp/django_cache',
 
'TIMEOUT': 3600,
 
'OPTIONS': {
 
'MAX_ENTRIES': 1000
 
}
 
}
 
}

全站缓存

 
#settings.py
 
CACHE_MIDDLEWARE_ALIAS = "default"
 
CACHE_MIDDLEWARE_SECONDS = 300
 
CACHE_MIDDLEWARE_KEY_PREFIX = '站点名'
 
 
MIDDLEWARE_CLASSES = (
 
'django.middleware.cache.UpdateCacheMiddleware',
 
'django.middleware.common.CommonMiddleware',
 
'django.middleware.cache.FetchFromCacheMiddleware',
 
)

用户页面

用户信息页面在登出后不能继续用缓存页面, 而要刷新

使用@vary_on_cookie装饰器

 
from django.views.decorators.vary import vary_on_cookie
 
from django.contrib.auth.decorators import login_required
 
 
@login_required(login_url="/login/")
 
@vary_on_cookie
 
def profile(request):
 
# do something here...
 
return HttpResponse(...)

页面级缓存

 
from django.views.decorators.cache import cache_page,cache_control
 
 
@cache_page(60*5)
 
@cache_control(must_revalidate=True,max_age=60*5)
 
def profile(request):
 
# do something here...
 
return HttpResponse(...)

基于类的视图缓存

 
from django.views.decorators.cache import cache_page,cache_control
 
from app.views import *
 
 
urlpatterns = [
 
url(r'^$',cache_page(60*5)(cache_control(must_revalidate=True,max_age=60*5)(IndexView.as_view()),name="index")),
 
]

刷新缓存

 
from django.core.cache import cache
 
from django.http import HttpRequest
 
from django.utils.cache import get_cache_key
 
 
def expire_page(request,path):
 
# The cache of request url after 'expire/' will be deleted,
 
# so you will get a fresh page !
 
request2 = HttpRequest()
 
request2.META['SERVER_NAME'] = request.META['SERVER_NAME']
 
request2.META['SERVER_PORT'] = request.META['SERVER_PORT']
 
request2.path = request.get_host()+'/'+path
 
print request2.build_absolute_uri()
 
key = get_cache_key(request2)
 
if cache.has_key(key):
 
cache.delete(key)
 
return HttpResponse("OK, the cache is refreshed")

本质上是利用HttpRequest伪造了一个与想要清除缓存的URL地址相同的请求,通过get_cache_key这个函数生成cache_key,然后删除对应的cache,达到刷新页面的效果。函数可以进一步改进至用户前台输入path,然后清除缓存后通过Ajax返回成功信息...

posted @   muzinan110  阅读(702)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示