Django Model Classes, Wrapt, and Decorator Variables

16 views
Skip to first unread message

Utkarsh Jadhav

unread,
Aug 10, 2015, 3:36:28 PM8/10/15
to Django users

Aim to achieve - Get call stacks where specific model classes are used. (Example -  MyModel.objects.save(), MyModel.objects.filter(), etc)

My Approach - 

Add this in order to override Save and Delete.
Class MyModelClass(CallStackMixin, models.Model)

In order to override get_query_set, I am overriding Model classes by
objects = CallStackManager()


In both CallStackManager and CallStackMixin I am calling capture_call_stack which eventually logs calls.

ex. 
class CallStackManager(Manager):
   
""" A Manager class which overrides the default Manager class for getting call stacks
    """

   
def get_query_set(self):
       
"""overriding the default queryset API method
        """

        capture_call_stack
(type(self))
       
return super(CallStackManager, self).get_query_set()

Also, I am defining a decorator @donottrack functionality where obvious calls to model classes are made. So that I would just log the new unique call stacks.

Definition for @donottrack is here -

def donottrack(*classes_not_to_be_tracked):
   
"""function decorator which deals with toggling call stack
    Args:
        classes_not_to_be_tracked: model classes where tracking is undesirable
    Returns:
        wrapped function
    """

   
@wrapt.decorator
   
def real_donottrack(wrapped, instance, args, kwargs):  # pylint: disable=W0613
       
"""takes function to be decorated and returns wrapped function


        Args:
            function - wrapped function i.e. real_donottrack
        """

       
global HALT_TRACKING  # pylint: disable=W0603
        HALT_TRACKING
.append(classes_not_to_be_tracked)
        HALT_TRACKING
[-1] = list(set([x for sublist in HALT_TRACKING for x in sublist]))
        return_value
= wrapped(*args, **kwargs)
        HALT_TRACKING
.pop()
       
return return_value
   
return real_donottrack

HALT_TRACKING here is global var which keeps track of model classes not to be tracked scoped to that particular function. 
Also, using Wrapt in order to retain identity of wrapped functions. 

Strangely,  HALT_TRACKING.pop() gets executed before the call to Save, delete or get_query_set is made.
Any idea why it is so?

Reply all
Reply to author
Forward
0 new messages