adding documentation for dump_json manage command
[oweals/karmaworld.git] / karmaworld / apps / courses / management / commands / import_json.py
1 import json
2 import os.path
3 import datetime
4
5 from django.core.management.base import BaseCommand
6 from django.core.files import File as DjangoFile
7
8 from karmaworld.apps.notes.models import *
9 # a little messy to import courses in a notes command?
10 from karmaworld.apps.courses.models import *
11
12 class Command(BaseCommand):
13     args = 'all [clean]'
14     help = """Import data to the database from .json. Expect the json in the 
15         format exported by the dump_json manage command.
16         The 'all' argument is required. When the 'all' argument is used, 
17         import_json expects the following files:
18             - schools.json
19             - courses.json
20             - notes.json
21         If an notes object in notes.json include a 'note_file' key, assume this 
22         file can be found relative to the following directory:
23             files/ 
24
25         If the optional 'clean' argument is specified, all notes, courses and 
26         files will be deleted from the db before importing 
27
28         When importing notes and courses, it is not currently possible to 
29         import ForeignKey values for schools or courses that have already been 
30         saved in the db. ForeignKey values within json files may only refer to 
31         id values included in the current batch of .json files
32     """
33
34     def handle(self, *args, **kwargs):
35
36         printl = self.stdout.write
37
38         if 'all' not in args:
39             printl('specify "all" - assumes schools.json, notes.json and courses.json')
40             return
41
42         if 'clean' in args:
43             for n in Note.objects.all(): n.delete()
44             for c in Course.objects.all(): c.delete()
45             for s in School.objects.all(): s.delete()
46
47         # read json files
48         with open('schools.json', 'r') as f:
49             school_dicts = json.load(f)
50
51         with open('notes.json', 'r') as f:
52             note_dicts = json.load(f)
53
54         with open('courses.json', 'r') as f:
55             course_dicts = json.load(f)
56
57         printl('Schools found: %d\n' % len(school_dicts))
58         printl('Notes found: %d\n' % len(note_dicts))
59         printl('Courses found: %d\n' % len(course_dicts))
60
61         # Store all the new School orm objects in a dictionary
62         schools_by_old_id = {}
63         courses_by_old_id = {}
64
65         #Schools
66         printl('Importing Schools\n')
67         for school in school_dicts:
68             old_id = school['id']
69             del school['id']
70             s = School(**school)
71             s.save()
72             schools_by_old_id[old_id] = s
73
74         # Courses
75         printl('Importing Courses\n')
76         for course in course_dicts:
77             #printl('Course: ' + course['name'] + '\n')
78             course['updated_at'] = datetime.datetime.utcnow()
79             course['created_at'] = datetime.datetime.utcnow()
80
81             # remove the old ids from the dict
82             old_id = course['id']
83             old_school_id = course['school_id']
84             del course['id']        # Have this auto generated
85             del course['school_id'] # use the actual school instead
86
87             c = Course(**course)
88             c.school = schools_by_old_id[old_school_id]
89             c.save()
90             courses_by_old_id[old_id] = c
91
92         # Notes
93         printl('Importing Notes\n')
94         for note in note_dicts:
95
96             # These keys cannot be pased as keyword arguments
97             tags = None
98             if 'tags' in note:
99                 tags = note['tags']
100                 del note['tags']
101
102             note_file = None
103             if 'note_file' in note and note['note_file']:
104                 note_file = os.path.join('files', note['note_file']) # specify folder for files
105                 del note['note_file']
106
107             # replace the string with this value
108             note['uploaded_at'] = datetime.datetime.utcnow()
109
110             old_course_id = note['course_id']
111             del note['id']
112             del note['course_id']
113
114             n = Note(**note)
115
116             n.course = courses_by_old_id[old_course_id]
117             n.save()
118
119             # Add the tags, if any
120             if tags:
121                 for t in tags: n.tags.add(t)
122
123             if note_file:
124                 printl(note_file + '\n')
125                 with open(note_file) as f:
126                     df = DjangoFile(f)
127                     _, file_name = os.path.split(note_file) # careful
128                     n.note_file.save(file_name, df)
129
130             n.save()
131
132         for c in Course.objects.all(): c.update_note_count()
133         for s in School.objects.all(): s.update_note_count()
134