annotate forums/management/commands/topic_export.py @ 1139:bb82177cc236

Issue #92 missing javascript for new post box.
author Brian Neal <bgneal@gmail.com>
date Thu, 27 Oct 2016 19:47:20 -0500
parents 4aadaf3bc234
children
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@647 8 from __future__ import with_statement
bgneal@646 9 from optparse import make_option
bgneal@646 10 import re
bgneal@646 11
bgneal@991 12 from django.conf import settings
bgneal@646 13 from django.core.management.base import LabelCommand, CommandError
bgneal@646 14 from django.template.loader import render_to_string, TemplateDoesNotExist
bgneal@646 15
bgneal@646 16 from forums.models import Topic
bgneal@646 17
bgneal@646 18
bgneal@646 19 SRC_RE = re.compile(r'src="/media/')
bgneal@991 20 SRC_REPL = 'src="{}://surfguitar101.com/media/'.format(settings.SITE_SCHEME)
bgneal@646 21
bgneal@646 22
bgneal@646 23 class Command(LabelCommand):
bgneal@646 24 help = "Exports a forum topic thread by rendering it through a given template"
bgneal@646 25 option_list = LabelCommand.option_list + (
bgneal@646 26 make_option('-t', '--template',
bgneal@646 27 default='forums/topic_export.html',
bgneal@646 28 help='template to render'),
bgneal@646 29 make_option('-o', '--output',
bgneal@646 30 default=None,
bgneal@646 31 help='output filename [default: stdout]'),
bgneal@646 32 )
bgneal@646 33
bgneal@646 34 def handle_label(self, tid, **opts):
bgneal@646 35 """Fetch the topic and related posts. Render through a template.
bgneal@646 36 Optionally write content to an output file.
bgneal@646 37
bgneal@646 38 """
bgneal@646 39 try:
bgneal@646 40 tid = int(tid)
bgneal@646 41 except ValueError:
bgneal@646 42 raise CommandError('topic ID must be an integer')
bgneal@646 43
bgneal@646 44 template_name = opts['template']
bgneal@646 45 output_filename = opts['output']
bgneal@646 46
bgneal@646 47 try:
bgneal@646 48 topic = Topic.objects.get(pk=tid)
bgneal@646 49 except Topic.DoesNotExist:
bgneal@646 50 raise CommandError('topic ID does not exist')
bgneal@646 51
bgneal@680 52 posts = topic.posts.select_related('user')
bgneal@646 53
bgneal@646 54 try:
bgneal@646 55 content = render_to_string(template_name, {'topic': topic, 'posts':
bgneal@646 56 posts})
bgneal@646 57 except TemplateDoesNotExist:
bgneal@646 58 raise CommandError('template does not exist')
bgneal@646 59
bgneal@646 60 # fix up smiley images
bgneal@646 61 content = SRC_RE.sub(SRC_REPL, content)
bgneal@646 62
bgneal@646 63 content = content.encode('utf-8')
bgneal@646 64
bgneal@646 65 if output_filename:
bgneal@646 66 with open(output_filename, 'w') as fp:
bgneal@646 67 fp.write(content)
bgneal@646 68 else:
bgneal@646 69 self.stdout.write(content)