summaryrefslogtreecommitdiff
path: root/exam/management/commands/results2csv.py
blob: 8d154e405cf06b538b46272538e30ac9d8ec1a07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# System library imports.
import sys
from os.path import basename

# Django imports.
from django.core.management.base import BaseCommand

# Local imports.
from exam.views import get_quiz_data
from exam.models import Quiz

def results2csv(filename, stdout):
    """Write exam data to a CSV file.  It prompts the user to choose the
    appropriate quiz.
    """
    qs = Quiz.objects.all()

    if len(qs) > 1:
        print "Select quiz to save:"
        for q in qs:
            stdout.write('%d. %s\n'%(q.id, q.description))
        quiz_id = int(raw_input("Please select quiz: "))
        try:
            quiz = Quiz.objects.get(id=quiz_id)
        except Quiz.DoesNotExist:
            stdout.write("Sorry, quiz %d does not exist!\n"%quiz_id)
            sys.exit(1)
    else:
        quiz = qs[0]

    paper_list = get_quiz_data(quiz.id)
    stdout.write("Saving results of %s to %s ... "%(quiz.description,
                                                    basename(filename)))
    f = open(filename, 'w')
    fields = ['name', 'username', 'rollno', 'email', 'answered', 'total',
              'attempts']
    SEP = ','
    f.write(SEP.join(['"%s"'%x for x in fields]) + '\n')
    for paper in paper_list:
        # name, username, rollno, email, answered
        f.write(SEP.join(['"%s"'%(paper[x]) for x in fields[:5]]) + SEP) 
        # total, attempts
        f.write(SEP.join(['%d'%(paper[x]) for x in fields[5:]]) + '\n')
    stdout.write('Done\n')
    
class Command(BaseCommand):
    args = '<results.csv>'
    help = '''Writes out the results of a quiz to a CSV file.  Prompt user
              to select appropriate quiz if there are multiple.
           '''
    
    def handle(self, *args, **options):
        """Handle the command."""
        # Save to file.
        results2csv(args[0], self.stdout)