comparison legacy/management/commands/import_old_links.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_links.py@639cfdf59167
children
comparison
equal deleted inserted replaced
580:c525f3e0b5d0 581:ee87ea74d46b
1 """
2 import_old_links.py - For importing links from SG101 1.0 as csv files.
3 """
4 from __future__ import with_statement
5 import csv
6 import datetime
7
8 from django.core.management.base import LabelCommand, CommandError
9 from django.contrib.auth.models import User
10
11 from weblinks.models import Link, Category
12
13
14 class Command(LabelCommand):
15 args = '<filename filename ...>'
16 help = 'Imports weblinks from the old database in CSV format'
17
18 def handle_label(self, filename, **options):
19 """
20 Process each line in the CSV file given by filename by
21 creating a new weblink object and saving it to the database.
22
23 """
24 self.cats = {}
25 try:
26 self.default_user = User.objects.get(pk=2)
27 except User.DoesNotExist:
28 raise CommandError("Need a default user with pk=2")
29
30 try:
31 with open(filename, "rb") as f:
32 self.reader = csv.DictReader(f)
33 try:
34 for row in self.reader:
35 self.process_row(row)
36 except csv.Error, e:
37 raise CommandError("CSV error: %s %s %s" % (
38 filename, self.reader.line_num, e))
39
40 except IOError:
41 raise CommandError("Could not open file: %s" % filename)
42
43 def get_category(self, row):
44 """
45 Return the Category object for the row.
46
47 """
48 cat_id = row['cid']
49 if cat_id not in self.cats:
50 try:
51 cat = Category.objects.get(pk=cat_id)
52 except Category.DoesNotExist:
53 raise CommandError("Category does not exist: %s on line %s" % (
54 cat_id, self.reader.line_num))
55 else:
56 self.cats[cat_id] = cat
57 return self.cats[cat_id]
58
59 def get_user(self, username):
60 """
61 Return the user object for the given username.
62 If the user cannot be found, self.default_user is returned.
63
64 """
65 try:
66 return User.objects.get(username=username)
67 except User.DoesNotExist:
68 return self.default_user
69
70 def process_row(self, row):
71 """
72 Process one row from the CSV file: create an object for the row
73 and save it in the database.
74
75 """
76 link = Link(category=self.get_category(row),
77 title=row['title'].decode('latin-1'),
78 url=row['url'].decode('latin-1'),
79 description=row['description'].decode('latin-1'),
80 user=self.get_user(row['submitter']),
81 date_added=datetime.datetime.strptime(row['date'], "%Y-%m-%d %H:%M:%S"),
82 hits=int(row['hits']),
83 is_public=True)
84 link.save()