Login

Management command decorator

Author:
eternicode
Posted:
August 31, 2010
Language:
Python
Version:
1.1
Tags:
decorator management command
Score:
2 (after 2 ratings)

A quick-and-dirty, and extremely simple, decorator to turn a simple function into a management command.

This still requires you to have the management directory structure, but allows you to name your primary method whatever you want, and encapsulates the basic functionality of an argument-accepting management commmand.

The function's docstring will be used for the command's help text if the help arg is not passed to the decorator.

Simple usage:

from myapp.utils import command

@command()
def my_command():
    print "Hello, world"

I'm not too familiar with the intricacies of decorators and management commands, so this could probably (most likely) be improved upon, but it's a start.

Update: I've taken this a bit farther and put my work up on bitbucket: https://bitbucket.org/eternicode/django-management-decorators/src

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.core.management.base import BaseCommand

def command(help=None, args=''):
    def _decorate(func):
        _args = args
        _help = help
        class Command(BaseCommand):
            help = _help if _help is not None else func.__doc__
            args = _args
            def handle(self, *args, **kwargs):
                return func(*args, **kwargs)
        func.func_globals['Command'] = Command
        return func
    return _decorate

More like this

  1. Management command which helps to find temlate files by skyjur 4 years, 8 months ago
  2. collectmedia command: Copy or link media files from installed apps by exogen 6 years, 11 months ago
  3. Safe template decorator by eternicode 3 years, 3 months ago
  4. Management command to list custom management commands by pbx 6 years, 2 months ago
  5. extras.py for management commands by dnordberg 8 years ago

Comments

gmandx (on August 31, 2010):

Well, some how (and I think it can be done) the decorator can introspect the function's positional arguments and keyword arguments, and then use those for the command's arguments and options, respectively. Then the only parameter needed for the decorator usage would be the help text.

#

eternicode (on August 31, 2010):

gmandx, interesting idea. I've done some light reading around, and it looks like the functools module has some stuff that could do this.

#

Please login first before commenting.