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