gpt4 book ai didi

Luffy /6/ 接口缓存

转载 作者:知者 更新时间:2024-03-13 01:17:09 25 4
gpt4 key购买 nike


接口缓存

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)),

]

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com