-
配置
# settings.py CACHES = { 'default':{ 'BACKEND':'django.core.cache.backends.db.DatabaseCache', 'LOCATION':'my_cache_table', } }#⽣成缓存表 python manage.py createcachetable
# CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #指定缓存使 ⽤的引擎 # 'LOCATION': '/var/tmp/django_cache', #指定缓存的路径 # 'TIMEOUT':300, #缓存超时时间(默认为300秒,None表示永 不过期) # 'OPTIONS':{ # 'MAX_ENTRIES': 300, # 最⼤缓存记录的数量(默认300) # 'CULL_FREQUENCY': 3, # 缓存到达最⼤个数之后,剔除缓存 个数的⽐例,即:1/CULL_FREQUENCY(默认3) # } # } # }
redis缓存 需要安装:pip3 install django-redis CACHES = { 'default':{ 'BACKEND':'django_redis.cache.RedisCache',#指定缓存类型 redis缓存 'LOCATION':'redis://:[email protected]:6379/1', #缓存地址,@前 ⾯是reids的密码,如果没有则去掉 # 'LOCATION':'redis://127.0.0.1:6379/1', # 没密码 } }
-
实现
# views.py from django.views.decorators.cache import cache_page @cache_page(60 * 0.5) #缓存过期时间 def dbcache(request): return render(request,'index.html',context={'content':77665})
{# 局部缓存 #} {% load cache %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% cache 30 'content' %} {{ content }} {% endcache %} </body> </html>
{# 全站缓存 #} MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', ..... 'django.middleware.cache.FetchFromCacheMiddleware', ] CACHE_MIDDLEWARE_SECONDS = 20 #设置超时时间 20秒
# ⼿动设置缓存 设置缓存:cache.set(key,value,timeout) 获取缓存:cache.get(key) def myCache(req): # 从缓存获取页面 mycache = cache.get('mycache') if mycache: print('⾛缓存了') html = mycache else: print('没⾛缓存') tem = loader.get_template('mycache.html') html = tem.render({'con':'缓存测试的模板'}) cache.set('mycache',html,60) return HttpResponse(html)
Django—缓存
猜你喜欢
转载自blog.csdn.net/piduocheng0577/article/details/105032086
今日推荐
周排行