urls
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include("App.urls"))
]
缓存
App.urls
from django.urls import path
from App import views
app_name='App'
urlpatterns = [
path('', views.index,name='index'),
path('all/',views.cache_all1, name='all'),
path('cachedata/',views.cache_data1,name='cache_data'),
]
App.views
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from datetime import datetime, timedelta
@cache_page(20)
def index(request):
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
pre_time = datetime.now() - timedelta(days=3)
pre_time = pre_time.strftime("%Y-%m-%d %H:%M:%S")
print(current_time,pre_time)
return render(request,'index.html',locals())
index.html
{% load cache %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>页面缓存</title>
</head>
<body>
<h2> {{ current_time }} </h2>
{% cache 10 'pre' %}
<h2>{{ pre_time }}</h2>
{% endcache %}
</body>
</html>
views视图与模版内二选一
全站缓存
settings
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',#必须是第一个中间件
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware', # 必须是最后一个中间件
]
CACHE_MIDDLEWARE_SECONDS = 20 #设置超时时间 20秒
App.urls
from django.urls import path
from App import views
app_name='App'
urlpatterns = [
path('', views.index,name='index'),
path('all/',views.cache_all1, name='all'),
path('cachedata/',views.cache_data1,name='cache_data'),
]
App.views
from datetime import datetime
from django.http import HttpResponse
def cache_all1(request):
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return HttpResponse(current_time)
数据库缓存
settings
# 数据库缓存配置
CACHES = {
'default':{
'BACKEND':'django.core.cache.backends.db.DatabaseCache',
'LOCATION':'my_cache_table',
}
}
# redis做缓存
CACHES = {
'default':{
'BACKEND':'django_redis.cache.RedisCache',#指定缓存类型 redis缓存
'LOCATION':'redis://@127.0.0.1:6379/1', #缓存地址,@前面是reids的密码,如果没有则去掉
# 'LOCATION':'redis://127.0.0.1:6379/1', # 没密码
}
}
App.urls
from django.urls import path
from App import views
app_name='App'
urlpatterns = [
path('', views.index,name='index'),
path('all/',views.cache_all1, name='all'),
path('cachedata/',views.cache_data1,name='cache_data'),
]
App.views
from App.models import User
from django.shortcuts import render
from django.core.cache import cache
def cache_data1(request):
# 首先判断数据是否在缓存中,如果在直接获取
users = cache.get('all_users')
if not users: # 如果不在缓存,查询数据库,将结果写入缓存
users = User.objects.all()
# cache可以直接把查询结果序列化
cache.set('all_users',users)
print("数据库")
print(users)
return render(request,'index1.html',locals())
App.models
from django.db import models
class User(models.Model):
uid = models.AutoField(primary_key=True)
username = models.CharField(unique=True, max_length=30)
password = models.CharField(max_length=128)
class Meta:
db_table = 'user'
index1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1" width="80%">
{% for user in users %}
<tr>
<td>{{ user.username }}</td>
<td>{{ user.password }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>