32

在我的 django 应用程序中,我正在编写一个自定义管理命令,它将根据传递的参数创建一个对象的实例,并可以根据是否传递一个选项将其保存到数据库中--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()
    # ...

但是,我无法找到 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

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

非常感谢

4

2 回答 2

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.")
于 2012-10-31T13:22:51.567 回答
20

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

关键字是最action能说明问题的,它配置了你想用那个选项做什么——它只是一个标志来做一些特殊的事情(a callback,即'--enable-feature')还是它应该接受一个参数,例如(store,即'-事情 10')。

考虑到这一点,考虑到这一点,其余选项会更有意义。通读“选项属性”以了解您列出的内容,然后“操作”以查看我上面提到的内容

于 2012-10-31T13:04:52.633 回答