11

Django 管理命令文档显示了在 app/management/commands 文件夹中创建的所有命令。是否可以将命令放入子文件夹中,例如 app/management/commands/install 和 app/management/commands/maintenance?这将如何完成?

4

2 回答 2

6

不幸的是,从 Django 1.4 开始,似乎没有办法做到这一点。django.core.management.__init__.py有这种方法的来源:

def find_commands(management_dir):
    """
    Given a path to a management directory, returns a list of all the command
    names that are available.

    Returns an empty list if no commands are defined.
    """
    command_dir = os.path.join(management_dir, 'commands')
    try:
        return [f[:-3] for f in os.listdir(command_dir)
                if not f.startswith('_') and f.endswith('.py')]
    except OSError:
       return []

如您所见,它只考虑直接在commands文件夹内的文件,而忽略任何子文件夹。然而,如果你以某种方式“猴子补丁”这个函数,其余的代码应该可以正常工作,因为实际创建Command实例的代码是这样的:

def load_command_class(app_name, name):
    """
    Given a command name and an application name, returns the Command
    class instance. All errors raised by the import process
    (ImportError, AttributeError) are allowed to propagate.
    """
    module = import_module('%s.management.commands.%s' % (app_name, name))
    return module.Command()

因此,如果您有一个名为subfolder.command它的命令,它将加载正确的脚本并实例化正确的类。

然而,从实际的角度来看,我认为这样做没有用。当然,使用“命名空间”命令会很好,但是如果需要,您可以随时为所有命令添加一些名称,使用其他名称作为分隔符(例如_)。命令名称长度 - 以及在终端中键入它们所需的击键次数 - 将是相同的......

于 2012-10-09T03:12:45.307 回答
0

这是我的例子:

app
- management
  - install
      __init__.py
      check1.py
  - maintenance
      __init__.py
      check2.py
  - commands
    __init__.py
    daily_cron.py

daily_cron.py我使用的:

 from app.management.install import check1
 from app.management.maintenance import check2
 
 flag = check1(args)
 flag2 = check2(args)

请记住在每个新文件夹中放置__init__.py空文件

于 2021-06-29T05:57:39.857 回答