generate_serial_numbers.py 1.91 KB
Newer Older
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 56 57 58 59 60 61 62 63 64 65
import os.path
from uuid import uuid4
from optparse import make_option

from django.utils.html import escape
from django.core.management.base import BaseCommand, CommandError

from xmodule.modulestore.django import modulestore

from licenses.models import CourseSoftware, UserLicense


class Command(BaseCommand):
    help = """Generate random serial numbers for software used in a course.

    Usage: generate_serial_numbers <course_id> <software_name> <count>

    <count> is the number of numbers to generate.

    Example:

       import_serial_numbers MITx/6.002x/2012_Fall matlab 100

    """
    args = "course_id software_id count"

    def handle(self, *args, **options):
        """
        """
        course_id, software_name, count = self._parse_arguments(args)

        software, _ = CourseSoftware.objects.get_or_create(course_id=course_id,
                                                           name=software_name)
        self._generate_serials(software, count)

    def _parse_arguments(self, args):
        if len(args) != 3:
            raise CommandError("Incorrect number of arguments")

        course_id = args[0]
        courses = modulestore().get_courses()
        known_course_ids = set(c.id for c in courses)

        if course_id not in known_course_ids:
            raise CommandError("Unknown course_id")

        software_name = escape(args[1].lower())

        try:
            count = int(args[2])
        except ValueError:
            raise CommandError("Invalid <count> argument.")

        return course_id, software_name, count

    def _generate_serials(self, software, count):
        print "Generating {0} serials".format(count)

        # add serial numbers them to the database
        for _ in xrange(count):
            serial = str(uuid4())
            license = UserLicense(software=software, serial=serial)
            license.save()

        print "{0} new serial numbers generated.".format(count)