dump_course_structure.py 4.19 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
"""
A Django command that dumps the structure of a course as a JSON object.

The resulting JSON object has one entry for each module in the course:

{
  "$module_url": {
    "category": "$module_category",
    "children": [$module_children_urls... ],
    "metadata": {$module_metadata}
  },

  "$module_url": ....
  ...
}

"""

import json
from optparse import make_option
from textwrap import dedent

from django.core.management.base import BaseCommand, CommandError

from xmodule.modulestore.django import modulestore
26
from xmodule.modulestore.inheritance import own_metadata, compute_inherited_metadata
27 28

from xblock_discussion import DiscussionXBlock
29
from xblock.fields import Scope
30
from opaque_keys import InvalidKeyError
31
from opaque_keys.edx.keys import CourseKey
32

33 34
FILTER_LIST = ['xml_attributes']
INHERITED_FILTER_LIST = ['children', 'xml_attributes']
35 36 37 38 39 40 41 42 43 44 45 46 47 48


class Command(BaseCommand):
    """
    Write out to stdout a structural and metadata information for a
    course as a JSON object
    """
    args = "<course_id>"
    help = dedent(__doc__).strip()
    option_list = BaseCommand.option_list + (
        make_option('--modulestore',
                    action='store',
                    default='default',
                    help='Name of the modulestore'),
49 50 51 52 53 54 55 56
        make_option('--inherited',
                    action='store_true',
                    default=False,
                    help='Whether to include inherited metadata'),
        make_option('--inherited_defaults',
                    action='store_true',
                    default=False,
                    help='Whether to include default values of inherited metadata'),
57 58 59 60 61 62 63
    )

    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("course_id not specified")

        # Get the modulestore
64

65
        store = modulestore()
66 67 68

        # Get the course data

69
        try:
70
            course_key = CourseKey.from_string(args[0])
71 72 73
        except InvalidKeyError:
            raise CommandError("Invalid course_id")

74
        course = store.get_course(course_key)
75 76 77
        if course is None:
            raise CommandError("Invalid course_id")

78 79
        # Precompute inherited metadata at the course level, if needed:

80 81 82
        if options['inherited']:
            compute_inherited_metadata(course)

83 84
        # Convert course data to dictionary and dump it as JSON to stdout

85
        info = dump_module(course, inherited=options['inherited'], defaults=options['inherited_defaults'])
86

87
        return json.dumps(info, indent=2, sort_keys=True, default=unicode)
88 89


90
def dump_module(module, destination=None, inherited=False, defaults=False):
91 92 93 94 95 96 97
    """
    Add the module and all its children to the destination dictionary in
    as a flat structure.
    """

    destination = destination if destination else {}

98
    items = own_metadata(module)
99

100
    # HACK: add discussion ids to list of items to export (AN-6696)
101
    if isinstance(module, DiscussionXBlock) and 'discussion_id' not in items:
102 103
        items['discussion_id'] = module.discussion_id

104
    filtered_metadata = {k: v for k, v in items.iteritems() if k not in FILTER_LIST}
105

106
    destination[unicode(module.location)] = {
107
        'category': module.location.category,
108
        'children': [unicode(child) for child in getattr(module, 'children', [])],
109
        'metadata': filtered_metadata,
110 111
    }

112
    if inherited:
113
        # When calculating inherited metadata, don't include existing
114 115 116 117 118 119 120 121 122
        # locally-defined metadata
        inherited_metadata_filter_list = list(filtered_metadata.keys())
        inherited_metadata_filter_list.extend(INHERITED_FILTER_LIST)

        def is_inherited(field):
            if field.name in inherited_metadata_filter_list:
                return False
            elif field.scope != Scope.settings:
                return False
123
            elif defaults:
124 125 126 127 128
                return True
            else:
                return field.values != field.default

        inherited_metadata = {field.name: field.read_json(module) for field in module.fields.values() if is_inherited(field)}
129
        destination[unicode(module.location)]['inherited_metadata'] = inherited_metadata
130

131
    for child in module.get_children():
132
        dump_module(child, destination, inherited, defaults)
133 134

    return destination