在我的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
make_option()是用于创建Option实例的工厂函数; 目前它是Option构造函数的别名.optparse的未来版本可能会将Option拆分为多个类,make_option()将选择正确的类进行实例化.不要直接实例化Option.
http://docs.python.org/2/library/optparse.html#option-attributes
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)
Tim*_*ony 20
optparse文档可能会更有帮助.您基本上是告诉管理功能您需要的每个选项应该做什么.
该action关键字是最有说服力的,它配置要与该选项做什么-它只是一个标志,做一些特别的东西(一个callback,即"--enable-功能"),或者它应该接受例如参数(store即'-things 10').
考虑到这一点,其余的选项在考虑到这一切时会更有意义.仔细阅读"选项属性"以获得对所列内容的解释,然后通过"操作"来查看我上面提到的内容
| 归档时间: |
|
| 查看次数: |
31576 次 |
| 最近记录: |