Skip to content
Advertisement

Django – how to access request body in a decorator?

I need to access the body of a request inside of a decorator, how can i do that?

I’m calling the cache_page decorator from get in a class based view. In order to perform some logic, i need to access the URL of the request in the decorator.

Here is my code:

def custom_cache_page(timeout, *, cache=None, key_prefix=None):
    #print(request)
    return decorator_from_middleware_with_args(CacheMiddleware)(
        page_timeout=85,
        cache_alias=cache,
        key_prefix=key_prefix,
    )


class Sales_View(APIView):
    http_method_names = ['get']

    @method_decorator(custom_cache_page(1.5))
    def get(self, request, format=None):
        ...

Edit: i tried to do that with @wraps

def custom_cache_page(view):
    @wraps(view)
    def inner(request, *args, **kwargs):
        return decorator_from_middleware_with_args(CacheMiddleware)(
            page_timeout=85,

        )
    return inner

Advertisement

Answer

You can define the decorator inside the custom_cache_page, like:

from functools import wraps

def custom_cache_page(timeout, *, cache=None, key_prefix=None):
    callto = decorator_from_middleware_with_args(CacheMiddleware)(
        page_timeout=85,
        cache_alias=cache,
        key_prefix=key_prefix,
    )
    def decorator(view):
        @wraps(view)
        def f(request, *args, **kwargs):
            print(request)
            return callto(view)(request, *args, **kwargs)
        return f
    return decorator
Advertisement