Home > Net >  Cache function or view?
Cache function or view?

Time:01-09

I want to use django-rest-framework with cache.

@cache_page(10 * 60)
@api_view(['GET'])
def get_num(request):
    if request.method == "GET":
        res = ["ok"]
        return Response(res)

It works well.

So actually I want to cache not view but function

@cache_page(10 * 60)
def getCalc(num):
    return num * 10


@api_view(['GET'])
def get_num(request):
    if request.method == "GET":
        res = getCalc(request.query_params.get('num'))
        return Response(res)

There comes error TypeError: _wrapped_view() missing 1 required positional argument: 'request'

Is it possible to use cache for function??

CodePudding user response:

you can use cachetools

@cachetools.func.ttl_cache(maxsize=10,ttl=10*6)
def getCalc(num):
    return num * 10

maxsize depends on your requirement.

CodePudding user response:

you can add request to function parameters:

@cache_page(10 * 60)
def getCalc(request, num):
    return num * 10


@api_view(['GET'])
def get_num(request):
    if request.method == "GET":
        res = getCalc(request, request.query_params.get('num'))
        return Response(res)
  •  Tags:  
  • Related