Luffy /6/ 接口缓存
作者:互联网
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)),
]
标签:缓存,cache,list,接口,BannerView,Luffy,banner,response 来源: https://www.cnblogs.com/48xz/p/16216343.html