annotate downloads/management/commands/dlcatreport.py @ 665:86d04190ff4e

For issue #43, create mgmt. command to cleanup orphan downloads.
author Brian Neal <bgneal@gmail.com>
date Fri, 24 May 2013 23:42:49 -0500
parents d6489e6a40f6
children 161b56849114
rev   line source
bgneal@527 1 """
bgneal@527 2 dlcatreport - a management command to produce a HTML report of all the downloads
bgneal@527 3 in a given category.
bgneal@527 4
bgneal@527 5 """
bgneal@634 6 from optparse import make_option
bgneal@634 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
bgneal@527 11 from downloads.models import Category, Download
bgneal@527 12
bgneal@527 13
bgneal@634 14 def print_titles(dls):
bgneal@634 15 """Print out the download titles"""
bgneal@634 16
bgneal@634 17 for dl in dls:
bgneal@634 18 print dl.title.encode('utf-8')
bgneal@634 19
bgneal@634 20
bgneal@527 21 class Command(LabelCommand):
bgneal@527 22 help = "Produce on standard output a report of all downloads in a category."
bgneal@527 23 args = "category-slug"
bgneal@527 24
bgneal@634 25 option_list = LabelCommand.option_list + (
bgneal@634 26 make_option('--titles-only',
bgneal@634 27 action='store_true',
bgneal@634 28 default=False,
bgneal@634 29 help='Output a text listing of titles only'),
bgneal@634 30 )
bgneal@634 31
bgneal@527 32 def handle_label(self, slug, **options):
bgneal@527 33 """
bgneal@527 34 Render a template using the downloads in a given category and send it to
bgneal@527 35 stdout.
bgneal@527 36
bgneal@527 37 """
bgneal@527 38 try:
bgneal@527 39 category = Category.objects.get(slug=slug)
bgneal@527 40 except Category.DoesNotExist:
bgneal@527 41 raise CommandError("category slug '%s' does not exist" % slug)
bgneal@527 42
bgneal@527 43 downloads = Download.public_objects.filter(category=category).order_by(
bgneal@527 44 'title').select_related()
bgneal@527 45
bgneal@634 46 if options.get('titles_only'):
bgneal@634 47 print_titles(downloads)
bgneal@634 48 return
bgneal@634 49
bgneal@527 50 report = render_to_string('downloads/commands/category_report.html', {
bgneal@527 51 'category': category,
bgneal@527 52 'downloads': downloads,
bgneal@527 53 })
bgneal@527 54
bgneal@527 55 # encode it ourselves since it can fail if you try to redirect output to
bgneal@527 56 # a file and any of the content is not ASCII...
bgneal@527 57 print report.encode('utf-8')
bgneal@527 58