区域信息加入缓存
考虑优化问题,我们每次访问网页,都会查询数据库,就很浪费
所以我们要加缓存
我们先要从redis中获取area_info这个值
如果这个值存在,我们直接使用这个值,并把这个值保存早redis中,设置过期时间
在常量中,我们设置一个地区有效过期时间
然后设置redis中地区的过期时间
这里返回的是json
我们还需要将数据转换成json字符串
下面就是我们完整的代码
@api.route("/areas")
def get_area_info():
"""获取城区信息"""
# 用redis中读取数据
try:
response_json = redis_store.get("area_info")
except Exception as e:
logging.error(e)
else:
# redis有缓存数据
if response_json is not None:
response_json = json.loads(response_json)
# print(response_json)
logging.info('redis cache')
# return response_json, 200, {"Content-Type": "application/json"}
return jsonify(errno=RET.OK, errmsg='OK', data=response_json['data'])
# 查询数据库,读取城区信息
try:
area_li = Area.query.all() # 列表
except Exception as e:
logging.error(e)
return jsonify(errno=RET.DBERR, errmsg='数据库异常')
area_dict_li = []
# print(area_li)
for area in area_li:
area_dict_li.append(area.to_dict())
# 将数据转成json字符串 {key:value} <= dict(key=value)
# response_dict = dict(errno=RET.OK, errmsg='OK', data=area_dict_li)
response_dict = dict(data=area_dict_li)
response_json = json.dumps(response_dict)
try:
redis_store.setex("area_info", constants.AREA_INFO_REDIS_CACHE_EXPIRES, response_json)
except Exception as e:
logging.error(e)
# return response_json, 200, {"Content-Type": "application/json"}
return jsonify(errno=RET.OK, errmsg='OK', data=area_dict_li)
还可以这么写
@api.route("/areas")
def get_area_info():
"""获取城区信息"""
# 用redis中读取数据
try:
response_json = redis_store.get("area_info")
except Exception as e:
logging.error(e)
else:
# redis有缓存数据
if response_json is not None:
# response_json = json.loads(response_json)
# print(response_json)
logging.info('redis cache')
return response_json, 200, {"Content-Type": "application/json"}
# return jsonify(errno=RET.OK, errmsg='OK', data=response_json['data'])
# 查询数据库,读取城区信息
try:
area_li = Area.query.all() # 列表
except Exception as e:
logging.error(e)
return jsonify(errno=RET.DBERR, errmsg='数据库异常')
area_dict_li = []
# print(area_li)
for area in area_li:
area_dict_li.append(area.to_dict())
# 将数据转成json字符串 {key:value} <= dict(key=value)
# response_dict = dict(errno=RET.OK, errmsg='OK', data=area_dict_li)
response_dict = dict(errno=RET.OK, errmsg='OK',data=area_dict_li)
response_json = json.dumps(response_dict)
try:
redis_store.setex("area_info", constants.AREA_INFO_REDIS_CACHE_EXPIRES, response_json)
except Exception as e:
logging.error(e)
return response_json, 200, {"Content-Type": "application/json"}
# return jsonify(errno=RET.OK, errmsg='OK', data=area_dict_li)