|
1 #! /usr/bin/python |
|
2 |
|
3 """Module to fill database with the tasks supplied in CSV. |
|
4 This module takes the directory containing the csv files as |
|
5 argument and creates task for the data in each CSV file in |
|
6 this directory. |
|
7 """ |
|
8 |
|
9 __authors__ = [ |
|
10 '"Madhusudan.C.S" <madhusudancs@gmail.com>' |
|
11 ] |
|
12 |
|
13 |
|
14 import csv |
|
15 import datetime |
|
16 import os |
|
17 import sys |
|
18 |
|
19 from django.contrib.auth.models import User |
|
20 |
|
21 from pytask.taskapp.models import Task |
|
22 |
|
23 |
|
24 STATIC_DATA = { |
|
25 'created_by': User.objects.get(pk=1), |
|
26 'creation_datetime': datetime.datetime.now() |
|
27 } |
|
28 |
|
29 |
|
30 def get_textbooks_from_csv(directory, file_name): |
|
31 """Return the list of the titles of tasks. |
|
32 |
|
33 Args: |
|
34 file: name of the CSV file from which tasks must be fetched. |
|
35 """ |
|
36 |
|
37 file_absolute_name = os.path.join(directory, file_name) |
|
38 |
|
39 csv_obj = csv.reader(open(file_absolute_name)) |
|
40 |
|
41 # Nifty trick to separate the file extension out and get the |
|
42 # remaining part of the filename to use this as the tag for |
|
43 # branches/departments |
|
44 branch_name = os.extsep.join(file_name.split(os.extsep)[:-1]) |
|
45 |
|
46 textbooks = [] |
|
47 for line in csv_obj: |
|
48 if len(line) == 2: |
|
49 sep = ' by ' |
|
50 else: |
|
51 sep = '' |
|
52 |
|
53 textbooks.append({ |
|
54 'title': sep.join(line), |
|
55 'desc': '(To be filled in by the Coordinator or the T/A.)', |
|
56 'tags_field': ', '. join(['Textbook', branch_name, line[1]]), |
|
57 'pynts': 10, |
|
58 }) |
|
59 |
|
60 return textbooks |
|
61 |
|
62 def seed_db(data): |
|
63 """Seeds the database when the data is passed as the argument |
|
64 |
|
65 Args: |
|
66 data: A dictionary containing the data to be seeded into the |
|
67 task model. |
|
68 """ |
|
69 |
|
70 for task in data: |
|
71 task.update(STATIC_DATA) |
|
72 task_obj = Task(**task) |
|
73 task_obj.save() |
|
74 |
|
75 def main(): |
|
76 """Just a wrapper function to make call the functions that perform |
|
77 the action. |
|
78 """ |
|
79 |
|
80 for dir in sys.argv[1:]: |
|
81 args = list(os.walk(dir)) |
|
82 files = args[0][2] |
|
83 for file_name in files: |
|
84 tasks = get_textbooks_from_csv(args[0][0], file_name) |
|
85 seed_db(tasks) |
|
86 |
|
87 if __name__ == '__main__': |
|
88 main() |