Last active
May 23, 2021 16:48
-
-
Save marcoala/a176ee0e75771a826a1197cc69336580 to your computer and use it in GitHub Desktop.
Base structure of a django management command, use transaction to rollback every change if an exception is raised and track time of execution.
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
import sys | |
import traceback | |
from django.utils import timezone | |
from django.db import transaction | |
from django.core.management.base import BaseCommand, CommandError | |
# django will strip new lines split helptext in 80 char lines | |
HELP_TEXT = """ | |
An explanation of the command puorpose, that will be printent when | |
$ ./manage.py help command_name | |
is called | |
""" | |
class Command(BaseCommand): | |
help = HELP_TEXT | |
_start_time = None | |
def add_arguments(self, parser): | |
parser.add_argument('--argument_name', type=str, default='default_value', help='Description of the argument') | |
def handle(self, *args, **options): | |
try: | |
with transaction.atomic(): | |
self.stdout.write('Starting command execution') | |
self._start_time = timezone.now() | |
# command body | |
self.stdout.write("Command execution completed successifly in {0}\n".format(self.elapsed_time())) | |
except Exception as e: # noqa | |
exc_type, exc_value, exc_traceback = sys.exc_info() | |
formatted_excption = traceback.format_exception(exc_type, exc_value, exc_traceback) | |
for line in formatted_excption: | |
self.stdout.write(line, ending='') | |
raise CommandError("An exception occurred. All operations aborted, database rolled back.\n") | |
def elapsed_time(self): | |
if self._start_time is None: | |
return None | |
return timezone.now() - self._start_time |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment