Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a custom management command with args and options - explanation of fields needed

Tags:

command

django

In my django app I am writing a custom management command which will create an instance of an object based on the args passed and have the option of saving it to the database based on whether an option --save is passed or not.

I've got a lot of help on this from the django documentation itself. Have also got important pointers from here about how to pass multiple arguments and here about how to have options.

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()     # ... 

However I am not able to find a detailed explanation of the fields in make_option. For example optparse.make_option lists

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 

In this help is self explanatory and I figured out what dest would mean, but I'm not clear what action='store_true' means. In fact it'd be great if someone could give me a short description of what all the arguments to make_option mean...

Thanks a lot

like image 693
mithril Avatar asked Oct 31 '12 12:10

mithril


People also ask

How do you pass arguments in Django management command?

The parameter parser is an instance of argparse. ArgumentParser (see the docs). Now you can add as many arguments as you want by calling parser 's add_argument method. In the code above, you are expecting a parameter n of type int which is gotten in the handle method from options .

What are management commands in Django?

Django management commands are included as part of Django apps and are designed to fulfill repetitive or complex tasks through a one keyword command line instruction. Every Django management command is backed by a script that contains the step-by-step Python logic to fulfill its duties.


2 Answers

Explanation of make_option from the docs http://docs.python.org/2/library/optparse.html#populating-the-parser

make_option() is a factory function for creating Option instances; currently it is an alias for the Option constructor. A future version of optparse may split Option into several classes, and make_option() will pick the right class to instantiate. Do not instantiate Option directly.

These are all of the possible option attributes:

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

Common Use in a django management command:

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.") 
like image 117
Francis Yaconiello Avatar answered Oct 22 '22 10:10

Francis Yaconiello


The optparse docs might be a little bit more helpful. You are basically telling the management function what each option you require should do.

The action keyword is the most telling and it configures what you want to do with that option - is it just a flag to do something special (a callback, i.e. '--enable-feature') or should it accept a parameter for example (store, i.e. '-things 10').

With that in mind, the rest of the options make a bit more sense with that all in mind. Read through 'option attributes' to get an explanation of what you've listed, and then 'actions' to see what I've mentioned above

like image 40
Timmy O'Mahony Avatar answered Oct 22 '22 09:10

Timmy O'Mahony