一、内置数据库缓存
-
1、首先创建一个数据库
-
2、创建一个缓存表 python manage.py createcachetable my_cache_table
-
3、项目目录结构:
自己配置好 appcache,urls 等 -
3、settings 配置
CACHES = {
'default':{
# django 内置缓存 数据库形式 性能相对较低
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table',
'TIMEOUT': 60 * 5
}
}
- 4、templates
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul>
{% for news in news_list %}
<li>{{ news }}</li>
{% endfor %}
</ul>
</body>
</html>
- 4、appcache.views
方式一:使用装饰器方式缓存
from django.core.cache import cache
from django.core.cache import caches
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from time import sleep
# Django 内置的数据库缓存 性能还是相对比较低
@cache_page(30)
def news(request):
news_list = []
for i in range(10):
news_list.append(f"这是新闻{i}")
sleep(5)
data = {
"news_list":news_list
}
return render(request,'news.html',context=data)
方式二:使用主动查询去缓存
def news2(request):
result = cache.get("news")
if result:
return HttpResponse(result)
news_list = []
for i in range(10):
news_list.append(f"这是新闻{i}")
sleep(5)
data = {
"news_list":news_list
}
response = render(request,'news.html',context=data)
cache.set("news",response.content,timeout=60)
return response
二、redis缓存数据
备注:其实就是把这个内容给替换一下,我这直接不替换了,直接再增加一个字典,redis的
- appcache.views
方式一:使用装饰器的方式缓存
@cache_page(30,cache='redis_backend')
def news3(request):
news_list = []
for i in range(10):
news_list.append(f"这是新闻{i}")
sleep(5)
data = {
"news_list":news_list
}
return render(request,'news.html',context=data)
方式二:使用主动查询方式缓存
def news4(request):
cache = caches['redis_backend']
result = cache.get("news")
if result:
return HttpResponse(result)
news_list = []
for i in range(10):
news_list.append(f"这是新闻{i}")
sleep(5)
data = {
"news_list":news_list
}
response = render(request,'news.html',context=data)
cache.set("news",response.content,timeout=60)
return response
小记:
1、当我们使用一种方式缓存:
views:
方式一:
-
from django.views.decorators.cache import cache_page
-
@cache_page(30)
方式二:
- from django.core.cache import cache
- result = cache.get(“news”)
- response = render(request,‘news.html’,context=data)
- cache.set(“news”,response.content,timeout=60)
2、当我们使用多种方式缓存:
views:
方式一:
- from django.views.decorators.cache import cache_page
- @cache_page(30,cache=‘redis_backend’)
方式二:
- from django.core.cache import caches
- cache = caches[‘redis_backend’]
- result = cache.get(“news”)
- response = render(request,‘news.html’,context=data)
- cache.set(“news”,response.content,timeout=60)
综上所述:还是装饰器方便,多种缓存也不怕
- from django.views.decorators.cache import cache_page
- @cache_page(30,cache=‘redis_backend’)