annotate downloads/management/commands/dlcatreport.py @ 1201:fe10aea76cbd tip

Add 2023 MP3 compilation links
author Brian Neal <bgneal@gmail.com>
date Sun, 24 Mar 2024 14:50:23 -0500
parents cb712b2c34af
children
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@1188 8 from django.core import serializers
bgneal@527 9 from django.core.management.base import LabelCommand, CommandError
bgneal@527 10 from django.template.loader import render_to_string
bgneal@527 11
bgneal@527 12 from downloads.models import Category, Download
bgneal@527 13
bgneal@527 14
bgneal@527 15 class Command(LabelCommand):
bgneal@527 16 help = "Produce on standard output a report of all downloads in a category."
bgneal@527 17 args = "category-slug"
bgneal@527 18
bgneal@634 19 option_list = LabelCommand.option_list + (
bgneal@634 20 make_option('--titles-only',
bgneal@634 21 action='store_true',
bgneal@634 22 default=False,
bgneal@634 23 help='Output a text listing of titles only'),
bgneal@1188 24 make_option('--json',
bgneal@1188 25 action='store_true',
bgneal@1188 26 default=False,
bgneal@1188 27 help='Output downloads in JSON format'),
bgneal@634 28 )
bgneal@634 29
bgneal@527 30 def handle_label(self, slug, **options):
bgneal@527 31 """
bgneal@527 32 Render a template using the downloads in a given category and send it to
bgneal@527 33 stdout.
bgneal@527 34
bgneal@527 35 """
bgneal@527 36 try:
bgneal@527 37 category = Category.objects.get(slug=slug)
bgneal@527 38 except Category.DoesNotExist:
bgneal@527 39 raise CommandError("category slug '%s' does not exist" % slug)
bgneal@527 40
bgneal@527 41 downloads = Download.public_objects.filter(category=category).order_by(
bgneal@527 42 'title').select_related()
bgneal@527 43
bgneal@634 44 if options.get('titles_only'):
bgneal@684 45 self.print_titles(downloads)
bgneal@634 46 return
bgneal@634 47
bgneal@1188 48 if options.get('json'):
bgneal@1188 49 self.print_json(downloads)
bgneal@1188 50 return
bgneal@1188 51
bgneal@527 52 report = render_to_string('downloads/commands/category_report.html', {
bgneal@527 53 'category': category,
bgneal@527 54 'downloads': downloads,
bgneal@527 55 })
bgneal@527 56
bgneal@874 57 self.stdout.write(report)
bgneal@527 58
bgneal@684 59 def print_titles(self, dls):
bgneal@684 60 """Print out the download titles"""
bgneal@684 61
bgneal@684 62 for dl in dls:
bgneal@874 63 self.stdout.write(dl.title)
bgneal@684 64
bgneal@1188 65 def print_json(self, dls):
bgneal@1188 66 """Output downloads in JSON format"""
bgneal@1188 67 data = serializers.serialize('json', dls)
bgneal@1188 68 self.stdout.write(data)
bgneal@684 69
bgneal@1188 70