使用方法:
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):
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装饰器可以接收两个参数
2、