Skip to content

middleware

django_spire.profiling.middleware

__all__ = ['ProfilingMiddleware'] module-attribute

ProfilingMiddleware

Bases: MiddlewareMixin

Source code in django_spire/profiling/middleware/profiling.py
def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
    super().__init__(get_response)

    configuration = {
        'PROFILING_DIR': os.getenv('PROFILING_DIR', '.profile'),
        'PROFILING_ENABLED': os.getenv('PROFILING_ENABLED', 'False') == 'True',
        'PROFILING_MAX_FILES': int(os.getenv('PROFILING_MAX_FILES', '10')),
        'PROFILE_THRESHOLD': float(os.getenv('PROFILE_THRESHOLD', '0')),
    }

    directory = configuration.get('PROFILING_DIR', '.profile')

    if isinstance(directory, str):
        if not Path(directory).is_absolute():
            current = Path.cwd()
            base = getattr(settings, 'BASE_DIR', current)
            directory = Path(base) / directory
        else:
            directory = Path(directory)

    self.directory = Path(directory)
    self.directory.mkdir(exist_ok=True)

    self.enabled = configuration.get('PROFILING_ENABLED', False)
    self.threshold = configuration.get('PROFILE_THRESHOLD', 0)
    self.maximum = configuration.get('PROFILING_MAX_FILES', 10)

    self.count = 0
    self.lock = threading.Lock()

directory = Path(directory) instance-attribute

enabled = configuration.get('PROFILING_ENABLED', False) instance-attribute

threshold = configuration.get('PROFILE_THRESHOLD', 0) instance-attribute

maximum = configuration.get('PROFILING_MAX_FILES', 10) instance-attribute

count = 0 instance-attribute

lock = threading.Lock() instance-attribute

process_view

Source code in django_spire/profiling/middleware/profiling.py
def process_view(
    self,
    request: HttpRequest,
    view_func: Callable[..., Any],
    args: tuple[Any, ...],
    kwargs: dict[str, Any]
) -> Any:
    if not settings.DEBUG:
        return None

    if not self.enabled:
        return None

    if self._should_skip(request):
        return None

    with self.lock:
        self.count = self.count + 1
        request._profiling_id = self.count

    profiler = Profiler(interval=0.001)
    start = time.time()
    profiler.start()

    try:
        response = view_func(request, *args, **kwargs)

        if hasattr(response, 'render'):
            response.render()
    except Exception:
        profiler.stop()
        duration = (time.time() - start) * 1000
        self._save_profile(profiler, request, duration)

        raise
    else:
        profiler.stop()
        duration = (time.time() - start) * 1000

        if duration >= self.threshold:
            self._save_profile(profiler, request, duration)

        return response