Django在前后端分离项目中,如何针对GET接口请求加入缓存机制

缓存装饰器

from django.core.cache import cache
from hashlib import md5
import json


def cache_response(view_func):
    """
    接口返回信息加入缓存机制
    :param view_func:
    :return:
    """
    def wrapped_view(request, *args, **kwargs):
        params = request.params
		# 这里将需要特殊处理的请求参数提出
        if 'access_token' in params.keys():
            del params['access_token']
        # 将请求信息转化成md5的信息摘要
        md5_key = md5(json.dumps(params, ensure_ascii=False).encode()).hexdigest()
        # 查看是否有缓存
        cache_response_info = cache.get(md5_key)
        if cache_response_info:  # 有缓存则直接返回
            return cache_response_info
        response = view_func(request, *args, **kwargs)
		# 将此次接口的范湖信息通过缓存存起来,global_settings.QUERY_CACHE_EXPIRE_TIME为在配置文件中加的缓存时间
        cache.set(md5_key, response, global_settings.QUERY_CACHE_EXPIRE_TIME)
        return response

    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)

说明

  • 针对GET接口请求,如果并发量很大可以考虑加入缓存机制
  • 要注意缓存中信息和数据库信息的同步
posted on 2022-02-18 14:08  JentZhang  阅读(195)  评论(0)    收藏  举报