annotate downloads/management/commands/dlcatreport.py @ 684:161b56849114

For Django 1.5: management commands should use self.stdout, etc. for output. Note that I did not update the legacy commands since it is likely I will never run or test these commands again.
author Brian Neal <bgneal@gmail.com>
date Fri, 23 Aug 2013 19:17:40 -0500
parents d6489e6a40f6
children b59c154d0163
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@527 14 class Command(LabelCommand):
bgneal@527 15 help = "Produce on standard output a report of all downloads in a category."
bgneal@527 16 args = "category-slug"
bgneal@527 17
bgneal@634 18 option_list = LabelCommand.option_list + (
bgneal@634 19 make_option('--titles-only',
bgneal@634 20 action='store_true',
bgneal@634 21 default=False,
bgneal@634 22 help='Output a text listing of titles only'),
bgneal@634 23 )
bgneal@634 24
bgneal@527 25 def handle_label(self, slug, **options):
bgneal@527 26 """
bgneal@527 27 Render a template using the downloads in a given category and send it to
bgneal@527 28 stdout.
bgneal@527 29
bgneal@527 30 """
bgneal@527 31 try:
bgneal@527 32 category = Category.objects.get(slug=slug)
bgneal@527 33 except Category.DoesNotExist:
bgneal@527 34 raise CommandError("category slug '%s' does not exist" % slug)
bgneal@527 35
bgneal@527 36 downloads = Download.public_objects.filter(category=category).order_by(
bgneal@527 37 'title').select_related()
bgneal@527 38
bgneal@634 39 if options.get('titles_only'):
bgneal@684 40 self.print_titles(downloads)
bgneal@634 41 return
bgneal@634 42
bgneal@527 43 report = render_to_string('downloads/commands/category_report.html', {
bgneal@527 44 'category': category,
bgneal@527 45 'downloads': downloads,
bgneal@527 46 })
bgneal@527 47
bgneal@527 48 # encode it ourselves since it can fail if you try to redirect output to
bgneal@527 49 # a file and any of the content is not ASCII...
bgneal@684 50 self.stdout.write(report.encode('utf-8'))
bgneal@527 51
bgneal@684 52 def print_titles(self, dls):
bgneal@684 53 """Print out the download titles"""
bgneal@684 54
bgneal@684 55 for dl in dls:
bgneal@684 56 self.stdout.write(dl.title.encode('utf-8'))
bgneal@684 57
bgneal@684 58