comparison gpp/legacy/management/commands/import_old_potd_comments.py @ 535:4021ea1045f7

Adding import commands for the 1.0 POTD & comments.
author Brian Neal <bgneal@gmail.com>
date Sat, 31 Dec 2011 21:34:17 +0000
parents
children eac0ce5e137d
comparison
equal deleted inserted replaced
534:98f5facc0030 535:4021ea1045f7
1 """
2 import_old_potd_comments.py - For importing comments on POTD's from SG101 1.0
3 as csv files.
4
5 """
6 from __future__ import with_statement
7 import csv
8 import optparse
9 import sys
10 from datetime import datetime
11
12 from django.core.management.base import LabelCommand, CommandError
13 from django.contrib.auth.models import User
14 from django.contrib.contenttypes.models import ContentType
15
16 from comments.models import Comment
17 from potd.models import Photo
18 import legacy.data
19 from legacy.html2md import MarkdownWriter
20
21
22 PHOTO_ID_OFFSET = 100
23 ID_OFFSET = 3000
24
25
26 class Command(LabelCommand):
27 args = '<filename filename ...>'
28 help = 'Imports POTD comments from the old database in CSV format'
29 option_list = LabelCommand.option_list + (
30 optparse.make_option("-p", "--progress", action="store_true",
31 help="Output a . after every 20 items to show progress"),
32 )
33 md_writer = MarkdownWriter()
34
35 def handle_label(self, filename, **options):
36 """
37 Process each line in the CSV file given by filename by
38 creating a new POTD comment.
39
40 """
41 self.show_progress = options.get('progress')
42 self.users = {}
43
44 try:
45 with open(filename, "rb") as f:
46 self.reader = csv.DictReader(f)
47 num_rows = 0
48 try:
49 for row in self.reader:
50 self.process_row(row)
51 num_rows += 1
52 if self.show_progress and num_rows % 20 == 0:
53 sys.stdout.write('.')
54 sys.stdout.flush()
55 except csv.Error, e:
56 raise CommandError("CSV error: %s %s %s" % (
57 filename, self.reader.line_num, e))
58
59 print
60
61 except IOError:
62 raise CommandError("Could not open file: %s" % filename)
63
64 def process_row(self, row):
65 """
66 Process one row from the CSV file: create a Comment object for
67 the row and save it in the database.
68
69 """
70 try:
71 user = self._get_user(row['username'].decode('latin-1'))
72 except User.DoesNotExist:
73 print "Could not find user %s for comment %s; skipping." % (
74 row['username'], row['cid'])
75 return
76
77 pid = int(row['pid']) + PHOTO_ID_OFFSET
78 try:
79 photo = Photo.objects.get(id=pid)
80 except Photo.DoesNotExist:
81 print "Could not find photo %s for comment %s; skipping." % (
82 pid, row['cid'])
83 return
84
85 comment = Comment(
86 id=int(row['cid']) + ID_OFFSET,
87 content_type=ContentType.objects.get_for_model(photo),
88 object_id=photo.id,
89 user=user,
90 comment=self.to_markdown(row['comment'].decode('latin-1')),
91 creation_date=datetime.strptime(row['date'], "%Y-%m-%d %H:%M:%S"),
92 ip_address='192.0.2.0', # TEST-NET
93 is_public=True,
94 is_removed=False,
95 )
96
97 comment.save()
98
99 def _get_user(self, username):
100 """
101 Returns the user object with the given username.
102 Throws User.DoesNotExist if not found.
103
104 """
105 try:
106 return self.users[username]
107 except KeyError:
108 pass
109
110 try:
111 user = User.objects.get(username=username)
112 except User.DoesNotExist:
113 old_name = username.lower()
114 try:
115 user = User.objects.get(
116 username=legacy.data.KNOWN_USERNAME_CHANGES[old_name])
117 except KeyError:
118 raise User.DoesNotExist
119
120 self.users[username] = user
121 return user
122
123 def to_markdown(self, s):
124
125 s = s.replace('\n', '\n<br />')
126 self.md_writer.reset()
127 self.md_writer.feed(s)
128 return self.md_writer.markdown()