【问题标题】:DRF-Extension cache ignoring query parametersDRF 扩展缓存忽略查询参数
【发布时间】:2017-08-23 09:47:45
【问题描述】:

我正在为 caching 我的 API 使用 drf-extension。但它与 cache_response 装饰器没有按预期工作。

它缓存了/api/get-cities/?country=india 的响应。但是当我点击/api/get-cities/?country=usa 时,我得到了相同的响应。

这里是示例代码:

settings.py

CACHES = {
   "default": {
       "BACKEND": "django_redis.cache.RedisCache",
       "LOCATION": "redis://127.0.0.1:6379/0",
       "OPTIONS": {
           "CLIENT_CLASS": "django_redis.client.DefaultClient"
       },
       "KEY_PREFIX": "city"
   }
}

REST_FRAMEWORK_EXTENSIONS = {
   'DEFAULT_USE_CACHE': 'default',
   'DEFAULT_CACHE_RESPONSE_TIMEOUT': 86400,
}

views.py

class GetCities(APIView):

    @cache_response()
    def get(self, request):
        country = request.GET.get("country", "")
        return get_cities_function(country)

请帮忙。

【问题讨论】:

    标签: python django caching redis drf-extensions


    【解决方案1】:

    我能够找到问题的解决方案。我使用 api 名称和参数名称(在我的例子中是国家/地区)的组合在 redis 中创建了自己的键。因此,当 API 被查询参数命中时,我会检查是否存在对应的键,如果存在则返回缓存的响应。

    class GetCities(APIView):
    
        def calculate_cache_key(self, view_instance, view_method, request, args, kwargs):
            api = view_instance.get_view_name().replace(' ', '')
            return "api:" + api + "country:" + str(request.GET.get("country", ""))
    
        @cache_response(key_func='calculate_cache_key')
        def get(self, request):
            country = request.GET.get("country", "")
            return get_cities_function(country)
    

    【讨论】:

      猜你喜欢
      • 2018-07-30
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-13
      • 2018-10-03
      • 1970-01-01
      相关资源
      最近更新 更多