1. 需求:
页面显示时,需要使用汉字显示,但是在进行点击后,需要用到编码搜索。
2. 说明:
image.png3. 核心代码:
for j in aggs[i]['buckets']:
if j['key']:
code_val = db_code_read_from_cache(j['key'])
if code_val:
# 缓存中读到数据
tmp_ret.setdefault('val', []).append({'key': code_val, 'val': j['doc_count']})
else:
# 缓存中没有数据,从数据库中获取数据,并且存入缓存,时限一天过期
code_val = NewDbs.objects.filter(code=j['key']).first().name_cn
# 以code为键
db_code_write_to_cache(j['key'], code_val)
# 以中文为键
db_name_write_to_cache(code_val, j['key'])
tmp_ret.setdefault('val', []).append({'key': code_val, 'val': j['doc_count']})
utils.py
from django.core.cache import cache
# 存储数据库缓存
from cykj.settings import DB_TIME_OUT
def db_code_read_from_cache(code):
key = 'db_code_' + code
val = cache.get(key)
if val:
return val
else:
return None
def db_code_write_to_cache(code, val):
key = 'db_code_' + code
cache.set(key, val, DB_TIME_OUT)
def db_name_read_from_cache(name):
key = 'db_name_' + name
val = cache.get(key)
if val:
return val
else:
return None
def db_name_write_to_cache(name, val):
key = 'db_name_' + name
cache.set(key, val, DB_TIME_OUT)
网友评论