annotate downloads/management/commands/dlwgetcat.py @ 581:ee87ea74d46b

For Django 1.4, rearranged project structure for new manage.py.
author Brian Neal <bgneal@gmail.com>
date Sat, 05 May 2012 17:10:48 -0500
parents gpp/downloads/management/commands/dlwgetcat.py@311c926dd218
children 161b56849114
rev   line source
bgneal@527 1 """
bgneal@527 2 dlwgetcat - a management command to produce a bash script that wgets all the
bgneal@527 3 files in a given category.
bgneal@527 4
bgneal@527 5 """
bgneal@527 6 import os.path
bgneal@527 7
bgneal@527 8 from django.core.management.base import LabelCommand, CommandError
bgneal@527 9 from django.template.loader import render_to_string
bgneal@527 10 from django.template.defaultfilters import slugify
bgneal@527 11 from django.contrib.sites.models import Site
bgneal@527 12 from django.conf import settings
bgneal@527 13
bgneal@527 14 from downloads.models import Category, Download
bgneal@527 15
bgneal@527 16
bgneal@527 17 class Command(LabelCommand):
bgneal@527 18 help = ("Produce on standard output a bash script that wgets all the files"
bgneal@527 19 " in a category. The files are downloaded with a slugified name.")
bgneal@527 20
bgneal@527 21 args = "category-slug"
bgneal@527 22
bgneal@527 23 def handle_label(self, slug, **options):
bgneal@527 24 """
bgneal@527 25 Render a template using the downloads in a given category and send it to
bgneal@527 26 stdout.
bgneal@527 27
bgneal@527 28 """
bgneal@527 29 try:
bgneal@527 30 category = Category.objects.get(slug=slug)
bgneal@527 31 except Category.DoesNotExist:
bgneal@527 32 raise CommandError("category slug '%s' does not exist" % slug)
bgneal@527 33
bgneal@527 34 downloads = Download.public_objects.filter(category=category).order_by(
bgneal@527 35 'title').select_related()
bgneal@527 36
bgneal@527 37 # Create new destination names for the files since the uploaders often
bgneal@527 38 # give the files terrible names. The new names will be slugified
bgneal@527 39 # versions of the titles, with the same extension.
bgneal@527 40
bgneal@527 41 for dl in downloads:
bgneal@527 42 ext = os.path.splitext(dl.file.name)[1]
bgneal@527 43 dl.dest_filename = slugify(dl.title) + ext
bgneal@527 44
bgneal@527 45 output = render_to_string('downloads/commands/wget_cat.html', {
bgneal@527 46 'downloads': downloads,
bgneal@528 47 'domain': Site.objects.get_current().domain,
bgneal@528 48 'MEDIA_URL': settings.MEDIA_URL,
bgneal@527 49 })
bgneal@527 50
bgneal@527 51 # encode it ourselves since it can fail if you try to redirect output to
bgneal@527 52 # a file and any of the content is not ASCII...
bgneal@527 53 print output.encode('utf-8')