Skip to content

profiling

dev_tool.services.django.profiling

__all__ = ['ProfilingService'] module-attribute

ProfilingService

Bases: BaseService

A service class for Django profiling operations using pyinstrument.

This class provides methods for managing Django profiling with pyinstrument which generates its own HTML visualizations.

The constructor for the ProfilingService class.

It initializes the profiling service with package managers and creates the profile output directory.

Source code in dev_tool/services/django/profiling/service.py
def __init__(self) -> None:
    """
    The constructor for the ProfilingService class.

    It initializes the profiling service with package managers and creates
    the profile output directory.
    """

    super().__init__()

    self.manager, self.fallback = PackageManagerFactory.create_package_manager()

    self.directory = BASE / '.profile'
    self.directory.mkdir(exist_ok=True)

directory = BASE / '.profile' instance-attribute

inject_profiling_middleware

A method that injects profiling middleware into the Django application.

This method sets environment variables for pyinstrument profiling.

Raises:

  • ProfilingMiddlewareError

    If middleware injection fails.

Source code in dev_tool/services/django/profiling/service.py
def inject_profiling_middleware(self) -> None:
    """
    A method that injects profiling middleware into the Django application.

    This method sets environment variables for pyinstrument profiling.

    :raises ProfilingMiddlewareError: If middleware injection fails.
    """

    try:
        self._install_pyinstrument()

        directory = str(self.directory)

        os.environ['PROFILING_DIR'] = directory
        os.environ['PROFILING_ENABLED'] = 'True'
    except Exception:
        message = 'Failed to inject profiling middleware'
        log.exception(message)

        raise ProfilingMiddlewareError(message) from None

open_profile_directory

A method that opens the profile directory in the system file browser.

Source code in dev_tool/services/django/profiling/service.py
def open_profile_directory(self) -> None:
    """A method that opens the profile directory in the system file browser."""

    try:
        open_directory_in_explorer(self.directory)
    except Exception:
        message = 'Failed to open profile directory'
        log.exception(message)