anexia / django-request-cache

A Django app that provides a new cache on every request object. The cache is only kept within the request/response cycle.
MIT License
27 stars 13 forks source link

Cached request method is running 3 times per request #11

Open danielbenami opened 3 years ago

danielbenami commented 3 years ago

image

Instance method is being called multiple time. E.g.

Class X()
    @cache_for_request
    def load_results_from_csv_data(self):
        csv = CSV.objects.filter(experiment_id = self.exp_id)
        print('csv query ran')
        return csv

This method is called from other instance methods of the same class. Though this latter method cannot be cached (it's returns a pandas dataframe) e.g.

Class X()
    def do_x(self):
        csv = self.load_results_from_csv_data()

Finally it is also called from other instance method, where an instance of Class X() is being injected as a dependency using 'django-injector', e.g.:

class Y():

    @inject
    def __init__(self, x_data: X): 
        self.x_data = x_data

        def z(self):
                self.x_data.do_x()

        def w(self):
                self.x_data.do_x()

Expected result: cached method is only run once per http request observed result: it runs 3 times. If I remove the cache decorator it runs 6 times, so it partially works.

LLyaudet commented 3 years ago

Hello,

How many instances of class X do you have for this request ? If you have 3 objects of class X, because of the dependency on "self.exp_id" in the method, it would explain that the method is called once for each object.

Best regards, Laurent Lyaudet