1+ import django
12from django .utils .translation import gettext_lazy as _ , ngettext
23
34from debug_toolbar .panels import Panel
@@ -34,27 +35,23 @@ def generate_stats(self, request, response):
3435
3536 def enable_instrumentation (self ):
3637 """Hook into task system to collect queued tasks"""
37- try :
38- import django
39-
40- if django .VERSION < (6 , 0 ):
41- return
42- from django .tasks import Task
38+ if self ._tasks_available is False :
39+ # Django tasks not available means that we cannot instrument
40+ return
41+ from django .tasks import Task
4342
44- print ("[TasksPanel] instrumentation enabled:" , hasattr (Task , "enqueue" ))
43+ print ("[TasksPanel] instrumentation enabled:" , hasattr (Task , "enqueue" ))
4544
46- # Store original enqueue method
47- if hasattr (Task , "enqueue" ):
48- self ._original_enqueue = Task .enqueue
45+ # Store original enqueue method
46+ if hasattr (Task , "enqueue" ):
47+ self ._original_enqueue = Task .enqueue
4948
50- def wrapped_enqueue (task , * args , ** kwargs ):
51- result = self ._original_enqueue (task , * args , ** kwargs ).return_value
52- self ._record_task (task , args , kwargs , result )
53- return result
49+ def wrapped_enqueue (task , * args , ** kwargs ):
50+ result = self ._original_enqueue (task , * args , ** kwargs ).return_value
51+ self ._record_task (task , args , kwargs , result )
52+ return result
5453
55- Task .enqueue = wrapped_enqueue
56- except (ImportError , AttributeError ):
57- pass
54+ Task .enqueue = wrapped_enqueue
5855
5956 def _record_task (self , task , args , kwargs , result ):
6057 """Record a task that was queued"""
@@ -75,13 +72,9 @@ def disable_instrumentation(self):
7572 except (ImportError , AttributeError ):
7673 pass
7774
78- def _check_tasks_available (self ):
75+ @property
76+ def _tasks_available (self ) -> bool :
7977 """Check if Django tasks system is available"""
80- try :
81- import django
82-
83- if django .VERSION < (6 , 0 ):
84- return False
85- return True
86- except (ImportError , AttributeError ):
78+ if django .VERSION < (6 , 0 ):
8779 return False
80+ return True
0 commit comments