Search code examples
djangotastypie

Tastypie - Calling dispatch of other resoueres Manually


I need to create an API(named Dummy) that connects to multiple other API's in order to apply filters

What i did was call the dispatch method on the main API's dispatch method. I changed the requests QUERY_STRING for each API that was being called

class DummyResource(MultipartResource, ModelResource):
    class Meta:
        queryset = Dummy.objects.all()
        resource_name = 'dummy'
        allowed_methods = ['get']

    def dispatch(self, request_type, request, **kwargs):
#Call the 1st API
        request.META['QUERY_STRING']='years_experience__in=2&production_2015__gt=105000'
        obj=APIONEResource()
        print 'Result'+str(obj.dispatch(request_type, request, **kwargs))

#Call the 2nd API    
        request.META['QUERY_STRING']='LOS__contains={2}&annual_production__in=4'
        obj=APITWOResource()
        print 'Result'+str(obj.dispatch(request_type, request, **kwargs))

    return super(DummyResource, self).dispatch(request_type, request, **kwargs)

Now when I call the 1st API everything works fine and I get the correct filtered result. But when I call the 2nd API it returns all the results without any filters. I can confirm that the QUERY_STRING was changed correctly and cannot understand why this doesnt work. I have tried reversing the calling order and the results are that the first time any API is called the filters are applied but the 2nd time it does not apply.

Any ideas ?


Solution

  • ok figured out what i was doing wrong. I was reusing the same request object for all dispatch methods. which meant the query filters did not change.

        def dispatch(self, request_type, request, **kwargs):
            import copy
            request2=copy.copy(request)
    
    #Call the 1st API
            request.META['QUERY_STRING']='years_experience__in=2&production_2015__gt=105000'
            obj=APIONEResource()
            print 'Result'+str(obj.dispatch(request_type, request, **kwargs))
    
    #Call the 2nd API    
            request2.META['QUERY_STRING']='LOS__contains={2}&annual_production__in=4'
            obj=APITWOResource()
            print 'Result'+str(obj.dispatch(request_type, request2, **kwargs))