【问题标题】:Can I have a folder instead file for a Django custom command?我可以为 Django 自定义命令创建一个文件夹而不是文件吗?
【发布时间】:2021-02-07 16:29:21
【问题描述】:

我知道创建自定义 Django 命令的唯一方法是将文件放在 project/app/management/commands 文件夹中,如下所示 project/app/management/commands/my_custom_command.py

但我想知道是否有办法创建一个目录(如 python 包)而不是单个文件。应该是这样的:

project
├── app
|   ├── management
|   |   └── commands
|   |       ├── my_custom_command
|   |       |   ├── __init__.py
|   |       |   └── ... (other stuff like settings and output files)
|   |       └── ...
|   └── ...
├── manage.py
└── ...

有办法做这样的事情吗?我认为可以通过将命令内容保存在 app 文件夹中来使用整个 app 文件夹来执行类似的操作,但我不喜欢这种解决方案。

澄清:我已经尝试使用包含__init__.py 文件的文件夹,但它不起作用。

【问题讨论】:

    标签: python django command structure customization


    【解决方案1】:

    不可能,包被排除在外,见django.core.management.find_commands

    在 Django 3.1.5 中是:

    def find_commands(management_dir):
        """
        Given a path to a management directory, return a list of all the command
        names that are available.
        """
        command_dir = os.path.join(management_dir, 'commands')
        return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])
                if not is_pkg and not name.startswith('_')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多