我在我的应用management/commands
目录下编写自定义django命令。目前我在该目录中有6个不同的文件。每个文件都有一个不同的命令,可以解决一个独特的需求。但是,有些实用程序对所有这些实用程序都是通用的。抽象掉这个通用代码的最佳方法是什么?
以下是一个例子:
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
答案 0 :(得分:4)
在management / commands文件夹中,创建文件_private.py:
#_private.py
from django.core.management.base import BaseCommand, CommandError
class SharedCommand(BaseCommand):
def check_validity(self, color):
...
其他文件导入此文件并继承SharedCommand:
# command01.py
from ._private import *
class Command(SharedCommand):
def handle(self, *args, **options):
...