django使用缓存之drf-extensions

使用方法:
1、直接添加装饰器@cache_response
该装饰器装饰的方法有两个要求:

  • 它必须是继承了rest_framework.views.APIView的类的方法
  • 它必须返回rest_framework.response.Response 的实例

 

例子:

from rest_framework.response import Response
from rest_framework import views
from rest_framework_extensions.cache.decorators import (
    cache_response
)
from myapp.models import City

class CityView(views.APIView):
    @cache_response()
    def get(self, request, *args, **kwargs):
        # values_list()从查询集中只返回指定的字段
        cities = City.objects.all().values_list('name', flat=True)
        return Response(cities)

如果您第一次请求视图,您将从SQL查询中获得它,(~60ms response time):

# Request
GET /cities/ HTTP/1.1
Accept: application/json

# Response
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8

['Moscow', 'London', 'Paris']

第二次请求将击中缓存。没有sql计算,没有数据库查询,(~30 ms response time):

# Request
GET /cities/ HTTP/1.1
Accept: application/json

# Response
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8

['Moscow', 'London', 'Paris']

总结:减少响应时间取决于API方法内部的计算复杂性。

 

cache_response装饰器可以接收两个参数:

@cache_response(timeout=60*60, cache='default')
  • timeout 缓存时间
  • cache 缓存使用的Django缓存后端(即CACHES配置中的键名称)

 如果在使用cache_response装饰器时未指明timeout或者cache参数,则会使用配置文件中的默认配置,可以通过如下方法指明:

# DRF扩展
REST_FRAMEWORK_EXTENSIONS = {
    # 缓存时间
    'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 60,
    # 缓存存储
    'DEFAULT_USE_CACHE': 'default',
}
  • DEFAULT_CACHE_RESPONSE_TIMEOUT 缓存有效期,单位秒
  • DEFAULT_USE_CACHE 缓存的存储方式,与配置文件中的CACHES的键对应。

注意,cache_response装饰器既可以装饰在类视图中的get方法上,也可以装饰在REST framework扩展类提供的list或retrieve方法上。使用cache_response装饰器无需使用method_decorator进行转换


2、

 

posted @ 2019-06-21 11:07  chjxbt  阅读(497)  评论(0编辑  收藏  举报