示例#1
0
    def import_xblock(self,
                      user_id,
                      course_key,
                      block_type,
                      block_id,
                      fields=None,
                      runtime=None,
                      **kwargs):
        """
        Split-based modulestores need to import published blocks to both branches
        """
        with self.bulk_operations(course_key):
            # hardcode course root block id
            if block_type == 'course':
                block_id = self.DEFAULT_ROOT_BLOCK_ID
            new_usage_key = course_key.make_usage_key(block_type, block_id)

            if self.get_branch_setting(
            ) == ModuleStoreEnum.Branch.published_only:
                # if importing a direct only, override existing draft
                if block_type in DIRECT_ONLY_CATEGORIES:
                    draft_course = course_key.for_branch(
                        ModuleStoreEnum.BranchName.draft)
                    with self.branch_setting(
                            ModuleStoreEnum.Branch.draft_preferred,
                            draft_course):
                        draft = self.import_xblock(user_id, draft_course,
                                                   block_type, block_id,
                                                   fields, runtime)
                        self._auto_publish_no_children(draft.location,
                                                       block_type, user_id)
                    return self.get_item(
                        new_usage_key.for_branch(
                            ModuleStoreEnum.BranchName.published))
                # if new to published
                elif not self.has_item(
                        new_usage_key.for_branch(
                            ModuleStoreEnum.BranchName.published)):
                    # check whether it's new to draft
                    if not self.has_item(
                            new_usage_key.for_branch(
                                ModuleStoreEnum.BranchName.draft)):
                        # add to draft too
                        draft_course = course_key.for_branch(
                            ModuleStoreEnum.BranchName.draft)
                        with self.branch_setting(
                                ModuleStoreEnum.Branch.draft_preferred,
                                draft_course):
                            draft = self.import_xblock(user_id, draft_course,
                                                       block_type, block_id,
                                                       fields, runtime)
                            return self.publish(draft.location,
                                                user_id,
                                                blacklist=EXCLUDE_ALL)

            # do the import
            partitioned_fields = self.partition_fields_by_scope(
                block_type, fields)
            course_key = self._map_revision_to_branch(
                course_key)  # cast to branch_setting
            return self._update_item_from_fields(
                user_id,
                course_key,
                BlockKey(block_type, block_id),
                partitioned_fields,
                None,
                allow_not_found=True,
                force=True) or self.get_item(new_usage_key)
    def xblock_from_json(self,
                         class_,
                         course_key,
                         block_key,
                         block_data,
                         course_entry_override=None,
                         **kwargs):
        """
        Load and return block info.
        """
        if course_entry_override is None:
            course_entry_override = self.course_entry
        else:
            # most recent retrieval is most likely the right one for next caller (see comment above fn)
            self.course_entry = CourseEnvelope(
                course_entry_override.course_key, self.course_entry.structure)

        definition_id = block_data.definition

        # If no usage id is provided, generate an in-memory id
        if block_key is None:
            block_key = BlockKey(block_data.block_type, LocalId())

        convert_fields = lambda field: self.modulestore.convert_references_to_keys(
            course_key,
            class_,
            field,
            self.course_entry.structure['blocks'],
        )

        if definition_id is not None and not block_data.definition_loaded:
            definition_loader = DefinitionLazyLoader(
                self.modulestore,
                course_key,
                block_key.type,
                definition_id,
                convert_fields,
            )
        else:
            definition_loader = None

        # If no definition id is provide, generate an in-memory id
        if definition_id is None:
            definition_id = LocalId()

        # Construct the Block Usage Locator:
        block_locator = course_key.make_usage_key(
            block_type=block_key.type,
            block_id=block_key.id,
        )

        converted_fields = convert_fields(block_data.fields)
        converted_defaults = convert_fields(block_data.defaults)
        if block_key in self._parent_map:
            parent_key = self._parent_map[block_key]
            parent = course_key.make_usage_key(parent_key.type, parent_key.id)
        else:
            parent = None
        try:
            kvs = SplitMongoKVS(definition_loader,
                                converted_fields,
                                converted_defaults,
                                parent=parent,
                                field_decorator=kwargs.get('field_decorator'))

            if InheritanceMixin in self.modulestore.xblock_mixins:
                field_data = inheriting_field_data(kvs)
            else:
                field_data = KvsFieldData(kvs)

            module = self.construct_xblock_from_class(
                class_,
                ScopeIds(None, block_key.type, definition_id, block_locator),
                field_data,
                for_parent=kwargs.get('for_parent'))
        except Exception:  # pylint: disable=broad-except
            log.warning("Failed to load descriptor", exc_info=True)
            return ErrorDescriptor.from_json(
                block_data,
                self,
                course_entry_override.course_key.make_usage_key(
                    block_type='error', block_id=block_key.id),
                error_msg=exc_info_to_str(sys.exc_info()))

        edit_info = block_data.edit_info
        module._edited_by = edit_info.edited_by  # pylint: disable=protected-access
        module._edited_on = edit_info.edited_on  # pylint: disable=protected-access
        module.previous_version = edit_info.previous_version
        module.update_version = edit_info.update_version
        module.source_version = edit_info.source_version
        module.definition_locator = DefinitionLocator(block_key.type,
                                                      definition_id)
        # decache any pending field settings
        module.save()

        # If this is an in-memory block, store it in this system
        if isinstance(block_locator.block_id, LocalId):
            self.local_modules[block_locator] = module

        return module
    def xblock_from_json(self,
                         class_,
                         course_key,
                         block_key,
                         json_data,
                         course_entry_override=None,
                         **kwargs):
        if course_entry_override is None:
            course_entry_override = self.course_entry
        else:
            # most recent retrieval is most likely the right one for next caller (see comment above fn)
            self.course_entry = CourseEnvelope(
                course_entry_override.course_key, self.course_entry.structure)

        definition_id = json_data.get('definition')

        # If no usage id is provided, generate an in-memory id
        if block_key is None:
            block_key = BlockKey(json_data['block_type'], LocalId())

        if definition_id is not None and not json_data.get(
                'definition_loaded', False):
            definition_loader = DefinitionLazyLoader(
                self.modulestore, course_key, block_key.type, definition_id,
                lambda fields: self.modulestore.convert_references_to_keys(
                    course_key,
                    self.load_block_type(block_key.type),
                    fields,
                    self.course_entry.structure['blocks'],
                ))
        else:
            definition_loader = None

        # If no definition id is provide, generate an in-memory id
        if definition_id is None:
            definition_id = LocalId()

        block_locator = BlockUsageLocator(
            course_key,
            block_type=block_key.type,
            block_id=block_key.id,
        )

        converted_fields = self.modulestore.convert_references_to_keys(
            block_locator.course_key,
            class_,
            json_data.get('fields', {}),
            self.course_entry.structure['blocks'],
        )
        if block_key in self._parent_map:
            parent_key = self._parent_map[block_key]
            parent = course_key.make_usage_key(parent_key.type, parent_key.id)
        else:
            parent = None
        kvs = SplitMongoKVS(definition_loader,
                            converted_fields,
                            parent=parent,
                            field_decorator=kwargs.get('field_decorator'))

        if InheritanceMixin in self.modulestore.xblock_mixins:
            field_data = inheriting_field_data(kvs)
        else:
            field_data = KvsFieldData(kvs)

        try:
            module = self.construct_xblock_from_class(
                class_,
                ScopeIds(None, block_key.type, definition_id, block_locator),
                field_data,
            )
        except Exception:
            log.warning("Failed to load descriptor", exc_info=True)
            return ErrorDescriptor.from_json(
                json_data,
                self,
                course_entry_override.course_key.make_usage_key(
                    block_type='error', block_id=block_key.id),
                error_msg=exc_info_to_str(sys.exc_info()))

        edit_info = json_data.get('edit_info', {})
        module._edited_by = edit_info.get('edited_by')
        module._edited_on = edit_info.get('edited_on')
        module.previous_version = edit_info.get('previous_version')
        module.update_version = edit_info.get('update_version')
        module.source_version = edit_info.get('source_version', None)
        module.definition_locator = DefinitionLocator(block_key.type,
                                                      definition_id)
        # decache any pending field settings
        module.save()

        # If this is an in-memory block, store it in this system
        if isinstance(block_locator.block_id, LocalId):
            self.local_modules[block_locator] = module

        return module