Coverage for django_query_capture/decorators.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2023-11-20 10:20 +0000

1""" 

2The highest level of module.<br> 

3It is a module responsible for both query capture, classification, and output. 

4""" 

5import typing 

6 

7from contextlib import ContextDecorator, ExitStack 

8 

9from django.utils.module_loading import import_string 

10 

11from django_query_capture.capture import native_query_capture 

12from django_query_capture.classify import CapturedQueryClassifier 

13from django_query_capture.presenter import BasePresenter 

14from django_query_capture.settings import get_config 

15 

16 

17class query_capture(ContextDecorator): 

18 def __init__( 

19 self, 

20 ignore_output: bool = False, 

21 ignore_patterns: typing.Optional[typing.List[str]] = None, 

22 ): 

23 """ 

24 Args: 

25 ignore_output: Flag to prevent output. 

26 ignore_patterns: A list of patterns to ignore IGNORE_SQL_PATTERNS of settings. 

27 """ 

28 self.ignore_output = ignore_output 

29 self.ignore_patterns = ignore_patterns or get_config()["IGNORE_SQL_PATTERNS"] 

30 self.presenter_cls: typing.Type[BasePresenter] = import_string( 

31 get_config()["PRESENTER"] 

32 ) 

33 

34 def __enter__(self) -> native_query_capture: 

35 r""" 

36 Call [native_query_capture.\_\_enter\_\_][capture.native_query_capture.__enter__] 

37 

38 Returns: 

39 [native_query_capture][capture.native_query_capture] 

40 """ 

41 self._exit_stack = ExitStack().__enter__() 

42 self.native_query_capture = native_query_capture() 

43 self._exit_stack.enter_context(self.native_query_capture) 

44 return self.native_query_capture 

45 

46 def __exit__(self, exc_type, exc_val, exc_tb): 

47 r""" 

48 Call [native_query_capture.\_\_exit\_\_][capture.native_query_capture.__exit__].<br> 

49 Run the [CapturedQueryClassifier][classify.CapturedQueryClassifier] to extract meaningful data and transfer the data to the Presenter.<br> 

50 Presenter can be changed in settings, and if [BasePresenter][presenter.base.BasePresenter] is inherited and implemented, the desired output can be generated. 

51 """ 

52 self.classifier = CapturedQueryClassifier( 

53 self.native_query_capture.captured_queries, 

54 ignore_patterns=self.ignore_patterns, 

55 )() 

56 if not self.ignore_output: 

57 self.presenter_cls(self.classifier).print() 

58 self._exit_stack.close()