Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading