0.效果展示
城市列表使用缓存的过程
1.后端代码
# coding:utf-8from . import api
from flask import g, current_app, jsonify, request, session
from ihome.utils.response_code import RET
from ihome.models import Area, House, Facility, HouseImage, User, Order
from ihome import db, constants, redis_store
from ihome.utils.commons import login_required
from ihome.utils.image_storage import storage
from datetime import datetime
import json@api.route("/areas")
def get_area_info():"""获取城区信息"""# 尝试从redis中读取数据try:resp_json = redis_store.get("area_info")except Exception as e:current_app.logger.error(e)else:if resp_json is not None:# redis有缓存数据current_app.logger.info("hit redis area_info")return resp_json, 200, {"Content-Type": "application/json"}# 查询数据库,读取城区信息try:area_li = Area.query.all()except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="数据库异常")area_dict_li = []# 将对象转换为字典for area in area_li:area_dict_li.append(area.to_dict())# 将数据转换为json字符串resp_dict = dict(errno=RET.OK, errmsg="OK", data=area_dict_li)resp_json = json.dumps(resp_dict)# 将数据保存到redis中try:redis_store.setex("area_info", constants.AREA_INFO_REDIS_CACHE_EXPIRES, resp_json)except Exception as e:current_app.logger.error(e)return resp_json, 200, {"Content-Type": "application/json"}
2.前端代码
注意此处使用art-template模板引擎渲染数据