Luffy /6/ 接口缓存

x33g5p2x  于2022-05-05 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(344)


接口缓存

Luffy /6/ 接口缓存

这里将banner图片作为缓存放入redis

视图

class BannerView(GenericViewSet,ListModelMixin):
    # qs对象可以像列表一样,切片
    queryset = Banner.objects.filter(is_delete=False, is_show=True).order_by('orders')[:settings.BANNER_COUNT]
    serializer_class = BannerSerializer

    def list(self, request, *args, **kwargs):  # 重写list设置缓存
        banner_list=cache.get('banner_cache_list')
        if not banner_list:   # 如果缓存中没有缓存,那么第一次走数据库,并放入缓存
            response = super().list(request, *args, **kwargs)
            print(response.data,'走了数据库')
            cache.set('banner_cache_list',response.data)
        else:  # 缓存中有banner,走缓存
            print('走了缓存')
            response = Response(data=banner_list)

        return response

路由

from django.urls import path, include
from rest_framework.routers import SimpleRouter
from .views import BannerView

router = SimpleRouter()
router.register('banner', BannerView, 'banner')
urlpatterns = [
    path('', include(router.urls)),

]

相关文章