Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abstract away command code in custom django commands

Tags:

python

django

I'm writing custom django commands under my apps management/commands directory. At the moment I have 6 different files in that directory. Each file has a different command that solves a unique need. However, there are some utilities that are common to all of them. What is the best way to abstract away this common code?

Below is an example:

load_colors

class Command(BaseCommand):
   def handle(self, *args, **options)
      ....code unique to colors
   def check_validity(self, color)
      ....#code common to both shades and colors

load_shades

 class Command(BaseCommand):
   def handle(self, *args, **options)
      ....#code unique to shades
   def check_validity(self, color)
      ....#code common to both shades and colors
like image 604
Anthony Avatar asked Sep 27 '22 08:09

Anthony


1 Answers

In the management/commands folder create the file _private.py:

#_private.py
from django.core.management.base import BaseCommand, CommandError

class SharedCommand(BaseCommand):
   def check_validity(self, color):
      ...

The in other files import this file and inherit SharedCommand:

# command01.py
from ._private import *

class Command(SharedCommand):
    def handle(self, *args, **options):
        ...
like image 104
Serjik Avatar answered Sep 30 '22 06:09

Serjik