How to wrap custom endpoints in Django Tastypie?

121 Views Asked by At

I want to add a dispatch method to some resource so I could use a wrapper decorator on it. The issue is that it only works on the CRUD operations and wont go into the dispatch method on 'original' endpoints:

class SomeResource(SomeBaseResource):
    class Meta(...): ...
    
    def get_something_extra(self, request, **kwargs):
        ...

    def patch_detail(self, request, **kwargs):
        ...

and the base resource:

class SomeBaseResource(ModelResource):
    class Meta(...): ...
    
    # the wrapper
    @decorator_to_wrap_all_methods_with(...)
    def dispatch(self, request_type, request, **kwargs):
         logger.info('Enter')
         response = super(SomeBaseResource, self).dispatch(request_type, request, **kwargs)
         logger.info('Exit')
         return response

So when I use patch request it is working as expected, but wont on calling the get_something_extra api.

How do I wrap ALL methods in resource?

1

There are 1 best solutions below

0
AudioBubble On BEST ANSWER

A workaround solution is to add Middleware:

MIDDLEWARE = (
'my.basic.BaseMiddleware',
...
)

class BaseMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    @decorator_to_wrap_all_methods_with(...)
    def __call__(self, request):
        response = self.get_response(request)
        return response