Python全系列 教程
3567个小节阅读:5930.4k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
建立项目
xxxxxxxxxx
django-admin startproject django_cache9
创建子应用(在项目目录下执行)
xxxxxxxxxx
python manager.py startapp cache_app
创建视图逻辑,修改django_cache9/cache_app/views.py
文件
xxxxxxxxxx
from django.http import JsonResponse
def get_result():
# 做一些费时,但是不经常变更的数据查询,运算等
time.sleep(5)
return 'lower level cache is ok!!!'
def index(request):
rs = get_result()
return HttpResponse(f"测试缓存:{rs}")
创建路由地址django_cache9/cache_app/urls.py
文件
xxxxxxxxxx
from django.urls import path
from . import views
urlpatterns = [
path('cache/', views.index, name='index'),
主应用加载子路由,修改django_cache9/django_cache9/urls.py
文件
xxxxxxxxxx
from django.urls import path,include
urlpatterns = [
path('', include('cache_app.urls')),
]
设置缓存配置,修改django_cache9/cache_app/settings.py
文件
xxxxxxxxxx
CACHES ={
'default':{
# 处理缓存的模块
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
# 缓存的地址
'LOCATION': 'redis://127.0.0.1:6379',
# 缓存的额外配置
'OPTIONS': {
'db': '6',
'parser_class': 'redis.connection.PythonParser',
'pool_class': 'redis.BlockingConnectionPool',
}
}
}
创建缓存工具类,创建django_cache9/my_cache.py
xxxxxxxxxx
from django.core.cache import cache
def get_cache_or_exc_func(key, func, *args, **kwargs):
""" 根据传入的key和func,先获取缓存的内容,没有则使用func计算,并保存
:param key: 缓存的key
:param func: 计算函数
:param args: 可变参数
:param kwargs: 可变关键字参数
:return: 缓存的内容或func计算的结果
"""
# 获取缓存中的变量
result = cache.get(key)
# 判断缓存中的变量是否存在
if result:
# 直接返回缓存的结果
return result
# 缓存中不存在
else:
# 计算数据,得到结果
result = func(*args, **kwargs)
# 将结果保存到缓存中
cache.set(key, result)
# 返回计算的结果
return result
修改业务视图类
xxxxxxxxxx
from django.http import JsonResponse
from django_cache9.my_cache import get_cache_or_exc_func
def get_result():
# 做一些费时,但是不经常变更的数据查询,运算等
time.sleep(5)
return 'lower level cache is ok!!!'
def lower_level_cache(request):
# 需要获取一个统计数据
result = get_cache_or_exc_func('lower_level_cache', get_result)
return JsonResponse({'result': result})