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