Last active
January 3, 2023 22:18
-
-
Save tclancy/4236077 to your computer and use it in GitHub Desktop.
Profiling Django Management Command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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)
Awesome! Updated to your since hopefully no one is still running Django 1.2 or whatever this was for.
:)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think if you add
action='store_true'
you could drop the=True
part on the command line.