gpt4 book ai didi

python - 如何在 django 命令中实现应用程序命名空间?

转载 作者:行者123 更新时间:2023-12-04 13:59:23 25 4
gpt4 key购买 nike

我想在像这样的命令中实现 django 应用程序命名空间

python manage.py appname:command --parameters


python manage.py appname:command:subcommand --parameters

我怎么能做到这一点?

最佳答案

Django 管理命令基于 Python 标准库中的 argparse(自 Django 1.10 [1] 起)。一种可能的解决方案是使用 subparser。 [2]
首先创建一个文件作为标准管理命令,例如:yourapp/management/commands/base.py .

from __future__ import annotations

from typing import Any, Callable, Dict

from django.core.management.base import BaseCommand


def create_resource(**options):
print("Creating resource %s" % options["name_of_resource_to_create"])


def delete_resource(**options):
print("Deleting resource %s" % options["name_of_resource_to_delete"])


SUBCOMMANDS_MAPPING: Dict[str, Callable[[Dict[str, Any]], None]] = {
"create_resource": create_resource,
"delete_resource": delete_resource,
}


class Command(BaseCommand):
def add_arguments(self, parser):
subparsers = parser.add_subparsers(
dest="subcommand",
title="positional arguments:",
description="Required positional arguments to specify subcommand to execute.",
required=True,
)

# Parser for create_resource:
parser_serve = subparsers.add_parser(name="create_resource")
parser_serve.add_argument("name_of_resource_to_create", type=str)

# Parser for delete_resource:
parser_serve = subparsers.add_parser(name="delete_resource")
parser_serve.add_argument("name_of_resource_to_delete", type=str)

def handle(self, *args, **options):
print('Base command')
SUBCOMMANDS_MAPPING[options.pop("subcommand")](**options)
我们添加了一个名为 subcommand 的子解析器.每个子命令都有自己单独的必需/可选参数。子命令名称将包含在 subcommand 中 key 。根据这个值,我们决定运行哪个函数。
这是帮助输出的样子:
$ python manage.py base --help

usage: manage.py base [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] {create_resource,delete_resource} ...

optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
-v {0,1,2,3}, --verbosity {0,1,2,3}
Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output
--settings SETTINGS The Python path to a settings module, e.g. "myproject.settings.main". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.
--pythonpath PYTHONPATH
A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".
--traceback Raise on CommandError exceptions
--no-color Don't colorize the command output.
--force-color Force colorization of the command output.
--skip-checks Skip system checks.

positional arguments::
Required positional arguments to specify subcommand to execute.

{create_resource,delete_resource}


$ python manage.py create_resource --help

usage: manage.py base create_resource [-h] name_of_resource_to_create

positional arguments:
name_of_resource_to_create

optional arguments:
-h, --help show this help message and exit
我在 Django 3.1 和 Python 3.9 中测试了这个解决方案。我的灵感来源是这个答案: https://stackoverflow.com/a/37414551/752142 .
  • [1] https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-10
  • [2] https://docs.python.org/3/library/argparse.html#sub-commands
  • 关于python - 如何在 django 命令中实现应用程序命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54339246/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com