【问题标题】:How does one use Django custom management command option?如何使用 Django 自定义管理命令选项?
【发布时间】:2010-11-17 18:51:52
【问题描述】:

Django 文档通过示例告诉我如何为我的 django 自定义管理命令添加选项:

from optparse import make_option

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--delete',
            action='store_true',
            dest='delete',
            default=False,
            help='Delete poll instead of closing it'),
    )

然后文档就停止了。如何为此类编写handle 方法来检查用户是否提供了--delete 选项?有时 Django 让简单的事情变得困难:-(

【问题讨论】:

    标签: django django-manage.py


    【解决方案1】:

    你可以这样做:

    from optparse import make_option
    
    class Command(BaseCommand):
        option_list = BaseCommand.option_list + (
            make_option('--del',
                action='store_true',
                help='Delete poll'),
            make_option('--close',
                action='store_true',
                help='Close poll'),
        )
    
        def handle(self, close, *args, **kwargs):
            del_ = kwargs.get('del')
    

    请注意,Python 中的一些关键字是保留的,因此您可以使用 **kwargs 处理这些关键字。否则,您可以使用普通参数(就像我对 close 所做的那样)

    【讨论】:

    • 保留字为deldelete 允许作为变量名。
    • 对于其他来到这个线程的人,这个资源也帮助了我:alexonlinux.com/…
    【解决方案2】:

    关于定义命令(键名,dest)和处理默认值(在make_option 和命令中)的一点建议:

    class Command(BaseCommand):
        option_list = BaseCommand.option_list + (
            make_option('--del',
                action='store_true',
                help='Delete all polls.',
                dest='your_name_for_delete',
                default=False),
            make_option('--close',
                action='store_true',
                help='Close all polls.'),
        )
    
        def handle(self, close, *args, **options):
            if options.get('your_name_for_delete'):
                Poll.objects.delete()
            if options.get('close', False):
                Poll.objects.update(closed=True)
    

    在 Django 代码中,您会发现“关键字参数”(**kwargs) 通常命名为 **options,这更具暗示性(我坚持这种命名约定)。

    默认值可以在make_option中指定,也可以通过dict.get方法指定, 允许使用默认值。

    如果您的 Command.handle 方法被手动调用,那么您没有理由不使用 both 默认值,而 **options 字典可能会缺少此条目。

    【讨论】:

      猜你喜欢
      • 2019-09-24
      • 1970-01-01
      • 2018-06-19
      • 2016-03-28
      • 1970-01-01
      • 2012-08-28
      • 2016-06-08
      • 2018-01-21
      • 2016-07-09
      相关资源
      最近更新 更多