views:

285

answers:

2

Can I call yui compressor: java -jar yuicompressor-x.y.z.jar [options] [input file] from a django management command and if so how do I go about doing it?

I develop locally on Window and host on Linux, so this seem like a solution that will work on both.

+1  A: 

Yes, but you have to write the command part yourself. The best way to go about this would be to see how the stock commands are implemented or look at a project like django-command-extensions

However, an even better solution (i.e. less work) would be to use a project like django-compress that already defines a management command synccompress that will call yui compressor.

Van Gale
+3  A: 

To expand on Van Gale's answer, it's most certainly possible. Here are the ingredients:

  • An app that is in INSTALLED APPS
  • The proper directory structure
  • A python file to act as the command which inherits off of a Django management command class

Here's generally how this works...

When manage.py runs, if it does not find the command say "manage.py yui_compress" it searches through the installed apps. It looks in each app to see if app.management.commands exists, and then checks if there is a file "yui_compress.py" in that module. If so, it will initiate the class in that python file and use that.

So, it ends up looking like this...

app
   \management
        \commands
            yui_compress.py

Where yui_compress.py contains...

from django.core.management.base import NoArgsCommand

class Command(NoArgsCommand):
    help = "Does my special action."
    requires_model_validation = False

    def handle_noargs(self, **options):
        # Execute whatever code you want here
        pass

Of course 'app' needs to be in thE INSTALLED APPS inside of settings.py.

But then, Van does make a good suggestion to find a tool which already does what you want. :)

T. Stone
+1 Nice answer, I was wanting to sketch out how to do a command but didn't have enough time.
Van Gale
Thanks for the answer. I understand how to setup the management commands, but was wondering about the: NoArgsCommand and what to put inside the: def handle_noargs method?
Joe
What goes in there is whatever code you want to be run when the command is run. Here's an example from South -- http://bitbucket.org/andrewgodwin/south/src/tip/south/management/commands/convert_to_south.py So in your case you could, for example, have it recursively search the MEDIA_ROOT folder, find all files ending in CSS, run them through the YUI compressor, then save them as [[originalname]]_compressed.css.
T. Stone
yeah, but how do I run the command: java -jar yuicompressor-x.y.z.jar from that method? Sorry, I just can't find an docs on NoArgsCommand stuff. Thanks!
Joe
It's just regular Python that you stick in there. For example, subprocess.Popen -- http://docs.python.org/library/subprocess.html#subprocess.call
T. Stone