Skip to content

Instantly share code, notes, and snippets.

@tclancy
Last active January 3, 2023 22:18
Show Gist options
  • Save tclancy/4236077 to your computer and use it in GitHub Desktop.
Save tclancy/4236077 to your computer and use it in GitHub Desktop.
Profiling Django Management Command
from cProfile import Profile
from django.core.management.base import BaseCommand
class ProfileEnabledBaseCommand(BaseCommand):
"""Enable profiling a command with --profile.
Requires child class to define _handle instead of handle.
via https://gist.github.com/dfrankow
"""
def add_arguments(self, parser):
parser.add_argument('--profile', action='store_true', default=False)
def handle(self, *args, **options):
if options.get('profile', False):
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.print_stats()
else:
self._handle(*args, **options)
@tclancy
Copy link
Author

tclancy commented Dec 7, 2012

With a little (lot) of help from http://stackoverflow.com/questions/1687125/how-to-profile-a-django-custom-management-command-exclusively-- I'm not sure that's the cleanest way to get the profile option in there, but it works. Need to call it with --profile=True to get the profiling info.

@Wilfred
Copy link

Wilfred commented Jan 23, 2013

Note that profiler.sort_stats doesn't work: http://stackoverflow.com/a/13690983

@dfrankow
Copy link

I think if you add action='store_true' you could drop the =True part on the command line.

@dfrankow
Copy link

Here's my code for Django 3.2:

from cProfile import Profile
from django.core.management.base import BaseCommand

class ProfileEnabledBaseCommand(BaseCommand):
    """Enable profiling a command with --profile.

    Requires child class to define _handle instead of handle.

    See also https://gist.github.com/tclancy/4236077
    """
    def add_arguments(self, parser):
        parser.add_argument('--profile', action='store_true', default=False)

    def handle(self, *args, **options):
        if options.get('profile', False):
            profiler = Profile()
            profiler.runcall(self._handle, *args, **options)
            profiler.print_stats()
        else:
            self._handle(*args, **options)

@tclancy
Copy link
Author

tclancy commented May 25, 2021

Awesome! Updated to your since hopefully no one is still running Django 1.2 or whatever this was for.

@dfrankow
Copy link

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment