annotate forums/management/commands/topic_export.py @ 646:73eb098761a1

Implement mgmt command to export forum topic. BB issue #36.
author Brian Neal <bgneal@gmail.com>
date Sat, 23 Mar 2013 13:18:08 -0500
parents
children 2a4e2e86c65e
rev   line source
bgneal@646 1 """
bgneal@646 2 topic_export.py
bgneal@646 3
bgneal@646 4 A management command to export a forum topic by rendering it through a given
bgneal@646 5 template.
bgneal@646 6
bgneal@646 7 """
bgneal@646 8 from optparse import make_option
bgneal@646 9 import re
bgneal@646 10
bgneal@646 11 from django.core.management.base import LabelCommand, CommandError
bgneal@646 12 from django.template.loader import render_to_string, TemplateDoesNotExist
bgneal@646 13
bgneal@646 14 from forums.models import Topic
bgneal@646 15
bgneal@646 16
bgneal@646 17 SRC_RE = re.compile(r'src="/media/')
bgneal@646 18 SRC_REPL = 'src="http://surfguitar101.com/media/'
bgneal@646 19
bgneal@646 20
bgneal@646 21 class Command(LabelCommand):
bgneal@646 22 help = "Exports a forum topic thread by rendering it through a given template"
bgneal@646 23 option_list = LabelCommand.option_list + (
bgneal@646 24 make_option('-t', '--template',
bgneal@646 25 default='forums/topic_export.html',
bgneal@646 26 help='template to render'),
bgneal@646 27 make_option('-o', '--output',
bgneal@646 28 default=None,
bgneal@646 29 help='output filename [default: stdout]'),
bgneal@646 30 )
bgneal@646 31
bgneal@646 32 def handle_label(self, tid, **opts):
bgneal@646 33 """Fetch the topic and related posts. Render through a template.
bgneal@646 34 Optionally write content to an output file.
bgneal@646 35
bgneal@646 36 """
bgneal@646 37 try:
bgneal@646 38 tid = int(tid)
bgneal@646 39 except ValueError:
bgneal@646 40 raise CommandError('topic ID must be an integer')
bgneal@646 41
bgneal@646 42 template_name = opts['template']
bgneal@646 43 output_filename = opts['output']
bgneal@646 44
bgneal@646 45 try:
bgneal@646 46 topic = Topic.objects.get(pk=tid)
bgneal@646 47 except Topic.DoesNotExist:
bgneal@646 48 raise CommandError('topic ID does not exist')
bgneal@646 49
bgneal@646 50 posts = topic.posts.select_related(depth=1)
bgneal@646 51
bgneal@646 52 try:
bgneal@646 53 content = render_to_string(template_name, {'topic': topic, 'posts':
bgneal@646 54 posts})
bgneal@646 55 except TemplateDoesNotExist:
bgneal@646 56 raise CommandError('template does not exist')
bgneal@646 57
bgneal@646 58 # fix up smiley images
bgneal@646 59 content = SRC_RE.sub(SRC_REPL, content)
bgneal@646 60
bgneal@646 61 content = content.encode('utf-8')
bgneal@646 62
bgneal@646 63 if output_filename:
bgneal@646 64 with open(output_filename, 'w') as fp:
bgneal@646 65 fp.write(content)
bgneal@646 66 else:
bgneal@646 67 self.stdout.write(content)