使用args和选项编写自定义管理命令 - 解释所需的字段

mit*_*ril 31 django command

在我的django应用程序中,我正在编写一个自定义管理命令,它将根据传递的args创建一个对象实例,并可以根据是否--save传递一个选项将其保存到数据库中.

我从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'),
    )

  def handle(self, *args, **options):
    # ...
    if options['delete']:
        poll.delete()
    # ...
Run Code Online (Sandbox Code Playgroud)

但是我无法找到make_option中字段的详细说明.例如optparse.make_option列表

Instance attributes:
_short_opts : [string]
_long_opts : [string]

action : string
type : string
dest : string
default : any
nargs : int
const : any
choices : [string]
callback : function
callback_args : (any*)
callback_kwargs : { string : any }
help : string
metavar : string
Run Code Online (Sandbox Code Playgroud)

在这help是自我解释,我想出了什么dest意思,但我不清楚是什么action='store_true'意思.事实上,如果有人能给我一个简短描述所有论点的make_option意思,那就太好了......

非常感谢

Fra*_*llo 34

来自文档http://docs.python.org/2/library/optparse.html#populating-the-parser的make_option说明

make_option()是用于创建Option实例的工厂函数; 目前它是Option构造函数的别名.optparse的未来版本可能会将Option拆分为多个类,make_option()将选择正确的类进行实例化.不要直接实例化Option.

这些都是可能的选项属性:

http://docs.python.org/2/library/optparse.html#option-attributes

django管理命令中的常见用法:

class Command(BaseCommand):
    help = "Command to import a list of X"
    option_list = BaseCommand.option_list + (
        make_option(
            "-f", 
            "--file", 
            dest = "filename",
            help = "specify import file", 
            metavar = "FILE"
        ),
    )

    option_list = option_list + (
        make_option(
            "-s", 
            "--slug", 
            dest = "category",
            help = "category slug", 
            metavar = "SLUG"
        ),
    )

    def handle(self, *args, **options):
            # make sure file option is present
            if options['filename'] == None :
                raise CommandError("Option `--file=...` must be specified.")

            # make sure file path resolves
            if not os.path.isfile(options['filename']) :
                raise CommandError("File does not exist at the specified path.")

            # make sure form option is present
            if options['category'] == None :
                raise CommandError("Option `--slug=...` must be specified.")
Run Code Online (Sandbox Code Playgroud)

  • 这在Django 1.8中不适用,因为它已被弃用.请在此页面上找到更多信息:https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/ (5认同)

Tim*_*ony 20

optparse文档可能会更有帮助.您基本上是告诉管理功能您需要的每个选项应该做什么.

action关键字是最有说服力的,它配置要与该选项做什么-它只是一个标志,做一些特别的东西(一个callback,即"--enable-功能"),或者它应该接受例如参数(store即'-things 10').

考虑到这一点,其余的选项在考虑到这一切时会更有意义.仔细阅读"选项属性"以获得对所列内容的解释,然后通过"操作"来查看我上面提到的内容