From 948c9a6d9f3c502f6656345fc7e7578cae9a7b72 Mon Sep 17 00:00:00 2001 From: RogerWork Date: Mon, 18 Dec 2023 16:43:06 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90redis=E7=9A=84=E5=AD=A6?= =?UTF-8?q?=E4=B9=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dingxin_toolbox_drf/settings.py | 21 +++++++++++++++++++++ update/views.py | 15 ++++++++++++--- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/dingxin_toolbox_drf/settings.py b/dingxin_toolbox_drf/settings.py index 17dc685..cd9a44a 100644 --- a/dingxin_toolbox_drf/settings.py +++ b/dingxin_toolbox_drf/settings.py @@ -88,6 +88,27 @@ DATABASES = { } } +CACHES = { + "default": { + 'BACKEND': 'django_redis.cache.RedisCache', + # "BACKEND": "django.core.cache.backends.redis.RedisCache", + "LOCATION": "redis://127.0.0.1:6379", + + "OPTIONS": { + "CLIENT_CLASS": "django_redis.client.DefaultClient", + + } + } +} + +REST_FRAMEWORK_EXTENSIONS = { + 'DEFAULT_CACHE_RESPONSE_TIMEOUT': 10 * 5, # 缓存时间 + 'DEFAULT_USE_CACHE': 'default', # 缓存存储 +} + +SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # 使用Redis做为session缓存 +SESSION_CACHE_ALIAS = 'default' # 指定本地session使用本地缓存名称是default + # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators diff --git a/update/views.py b/update/views.py index 6b79de8..61a4bf9 100644 --- a/update/views.py +++ b/update/views.py @@ -1,13 +1,18 @@ from django.http import JsonResponse from django.db.models import Q -from rest_framework import viewsets, permissions, status +from rest_framework import viewsets, permissions, status, filters from update.models import Cinema from update.serializers import CinemaSerializer from rest_framework.views import APIView from rest_framework.response import Response +from rest_framework_extensions.cache.mixins import CacheResponseMixin +from django.utils.decorators import method_decorator +from django.views.decorators.cache import cache_page +from django_filters.rest_framework import DjangoFilterBackend -class CinemaViewSet(viewsets.ModelViewSet): +# CacheResponseMixin 一定要放第一位 +class CinemaViewSet(CacheResponseMixin, viewsets.ModelViewSet): # 接口文档的中文注释 """ create: 添加测试影院 @@ -19,9 +24,13 @@ class CinemaViewSet(viewsets.ModelViewSet): queryset = Cinema.objects.all() serializer_class = CinemaSerializer permission_classes = (permissions.IsAuthenticated,) + filter_backends = (filters.SearchFilter, DjangoFilterBackend) + search_fields = ('ip', 'sys_ver') + # filter_fields = ('ip', 'sys_ver') -class CinemaSearchAPIView(APIView): +class CinemaSearchAPIView(APIView, CacheResponseMixin): + @method_decorator(cache_page(60 * 5)) def get(self, request, *args, **kwargs): query_params = request.query_params.dict() print(query_params)