comparison legacy/management/commands/import_old_download_comments.py @ 581:ee87ea74d46b

For Django 1.4, rearranged project structure for new manage.py.
author Brian Neal <bgneal@gmail.com>
date Sat, 05 May 2012 17:10:48 -0500
parents gpp/legacy/management/commands/import_old_download_comments.py@4021ea1045f7
children
comparison
equal deleted inserted replaced
580:c525f3e0b5d0 581:ee87ea74d46b
1 """
2 import_old_download_comments.py - For importing download comments from SG101 1.0
3 as csv files.
4
5 """
6 from __future__ import with_statement
7 import csv
8 from datetime import datetime
9
10 from django.core.management.base import LabelCommand, CommandError
11 from django.contrib.auth.models import User
12 from django.contrib.contenttypes.models import ContentType
13
14 from downloads.models import Download, VoteRecord
15 from comments.models import Comment
16 from legacy.html2md import MarkdownWriter
17 import legacy.data
18
19
20 class Command(LabelCommand):
21 args = '<filename filename ...>'
22 help = 'Imports download comments from the old database in CSV format'
23 md_writer = MarkdownWriter()
24
25 def handle_label(self, filename, **options):
26 """
27 Process each line in the CSV file given by filename by
28 creating a new object and saving it to the database.
29
30 """
31 try:
32 with open(filename, "rb") as f:
33 self.reader = csv.DictReader(f)
34 try:
35 for row in self.reader:
36 self.process_row(row)
37 except csv.Error, e:
38 raise CommandError("CSV error: %s %s %s" % (
39 filename, self.reader.line_num, e))
40
41 except IOError:
42 raise CommandError("Could not open file: %s" % filename)
43
44 def process_row(self, row):
45 """
46 Process one row from the CSV file: create an object for the row
47 and save it in the database.
48
49 """
50 dl_id = int(row['ratinglid'])
51 if dl_id in (1, 2, 3, 4):
52 return
53
54 try:
55 dl = Download.objects.get(pk=dl_id)
56 except Download.DoesNotExist:
57 return
58
59 try:
60 user = User.objects.get(username=row['ratinguser'])
61 except User.DoesNotExist:
62 old_name = row['ratinguser'].lower()
63 try:
64 user = User.objects.get(
65 username=legacy.data.KNOWN_USERNAME_CHANGES[old_name])
66 except (User.DoesNotExist, KeyError):
67 return
68
69 vote_date = datetime.strptime(row['ratingtimestamp'], "%Y-%m-%d %H:%M:%S")
70
71 comment_text = row['ratingcomments'].decode('latin-1').strip()
72 if comment_text:
73 comment = Comment(
74 content_type=ContentType.objects.get_for_model(dl),
75 object_id=dl.id,
76 user=user,
77 comment=comment_text,
78 creation_date=vote_date,
79 ip_address = row['ratinghostname'],
80 is_public = True,
81 is_removed = False,
82 )
83 comment.save()
84
85 vr = VoteRecord(download=dl, user=user, vote_date=vote_date)
86 vr.save()
87
88 def to_markdown(self, s):
89 self.md_writer.reset()
90 self.md_writer.feed(s)
91 return self.md_writer.markdown()