应用名/views.py(视图,cache,缓存数据):
from django.shortcuts import render
from django.views.generic import View
from django.core.cache import cache # 导入缓存
# 类视图 (缓存数据库中的数据)
class IndexView(View):
'''显示首页'''
def get(self, request):
# 尝试从缓存中获取数据。 (如果数据库中有数据,就直接返回,不用再查数据库了)
context = cache.get('index_page_data') # 如果缓存中没有数据,返回None
if context is None:
# 如果缓存中没有数据
# 从数据库中查询数据。
index_data = 'xxxxx' # 从数据库中查询首页的公共数据。
context = {'comm_data': index_data}
# 设置缓存 (缓存所有用户公共的数据)
cache.set('index_page_data', context, 3600) # 3600表示过期时间,None表示永不过期。
# 清除首页的缓存数据
# cache.delete('index_page_data')
# 获取用户各自不同的数据
my_data = 'xxxxxx' # 从数据库中查询用户数据。 (不需要缓存)