一:通读策略的流程图:

二:查询省级信息,加缓存和没有加缓存代码比较:
1:没有加缓存
class ProvinceAreasView(View):
def get(self, request):
try:
p_data = Area.objects.filter(parent__isnull=True)
except Exception as e:
return JsonResponse({
"code": 400,
"errmsg": "查询数据库报错"
})
p_list = []
for p in p_data:
p_list.append({
"id": p.id,
"name": p.name,
})
return JsonResponse({
"code": 0,
"errmsg": "ok",
"province_list": p_list
})
2:增加缓存:
首先确定我要将什么数据写入缓存----p_list,
class ProvinceAreasView(View):
def get(self, request):
# 1:首先读缓存
p_list = cache.get('p_list')
if not p_list:
# 2:读不到读数据库
try:
p_data = Area.objects.filter(parent__isnull=True)
except Exception as e:
return JsonResponse({
"code": 400,
"errmsg": "查询数据库报错"
})
p_list = []
for p in p_data:
p_list.append({
"id": p.id,
"name": p.name,
})
# 3:回填到缓存中
cache.set("p_list", p_list, 3600)
return JsonResponse({
"code": 0,
"errmsg": "ok",
"province_list": p_list
})
3:测试:

三: 市区信息的缓存配置:
1:没有加缓存:
class SubAreasView(View):
def get(self, request, pk):
try:
# 查询父级的对象
parent_model = Area.objects.get(pk=pk)
# 查询子级的对象
sub_model_list = Area.objects.filter(parent_id= pk)
except Exception as e:
return JsonResponse({
"code": 200,
"errmsg": "查询数据库报错"
})
sub_list = []
for sub_model in sub_model_list:
sub_list.append({
"id": sub_model.id,
"name": sub_model.name,
})
# 构造响应数据:
sub_data = {
"id": parent_model.id,
"name": parent_model.name,
"subs": sub_list,
}
return JsonResponse({
"code": 0,
"errmsg": 200,
"sub_data": sub_data
})
2:加缓存之后:
class SubAreasView(View):
def get(self, request, pk):
parent_model = Area.objects.get(pk=pk)
# 1: 读缓存
sub_data = cache.get("sub_data_%d"% parent_model.id)
if not sub_data:
try:
# 查询子级的对象
sub_model_list = Area.objects.filter(parent_id= pk)
except Exception as e:
return JsonResponse({
"code": 200,
"errmsg": "查询数据库报错"
})
sub_list = []
for sub_model in sub_model_list:
sub_list.append({
"id": sub_model.id,
"name": sub_model.name,
})
# 2:写缓存
sub_data = {
"id": parent_model.id,
"name": parent_model.name,
"subs": sub_list}
# 3:回填缓存
cache.set("sub_data_%s"% parent_model.id, sub_data, 3600)
# 构造响应数据:
return JsonResponse({
"code": 0,
"errmsg": 200,
"sub_data": sub_data
})
3:测试:

浙公网安备 33010602011771号