From 0b2b9fe2e832c0b420126dcc22c629a635ccb1a3 Mon Sep 17 00:00:00 2001 From: "E. Kolpakov" Date: Wed, 15 Apr 2015 12:53:15 +0300 Subject: [PATCH] Added management command to manually reindex libraries --- .../management/commands/reindex_library.py | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 cms/djangoapps/contentstore/management/commands/reindex_library.py diff --git a/cms/djangoapps/contentstore/management/commands/reindex_library.py b/cms/djangoapps/contentstore/management/commands/reindex_library.py new file mode 100644 index 0000000000..fcba172c76 --- /dev/null +++ b/cms/djangoapps/contentstore/management/commands/reindex_library.py @@ -0,0 +1,75 @@ +from django.core.management import BaseCommand, CommandError +from optparse import make_option +from textwrap import dedent + +from contentstore.courseware_index import LibrarySearchIndexer + +from opaque_keys.edx.keys import CourseKey +from opaque_keys import InvalidKeyError +from opaque_keys.edx.locations import SlashSeparatedCourseKey +from opaque_keys.edx.locator import LibraryLocator + +from .prompt import query_yes_no + +from xmodule.modulestore.django import modulestore + + +class Command(BaseCommand): + """ + Command to reindex content libraries (single, multiple or all available) + + Examples: + + ./manage.py reindex_library lib1 lib2 - reindexes libraries with keys lib1 and lib2 + ./manage.py reindex_library --all - reindexes all available libraries + """ + help = dedent(__doc__) + + can_import_settings = True + + args = "" + + option_list = BaseCommand.option_list + ( + make_option( + '--all', + action='store_true', + dest='all', + default=False, + help='Reindex all libraries' + ),) + + def _parse_library_key(self, raw_value): + """ Parses library key from string """ + try: + result = CourseKey.from_string(raw_value) + except InvalidKeyError: + result = SlashSeparatedCourseKey.from_deprecated_string(raw_value) + + if not isinstance(result, LibraryLocator): + raise CommandError("Argument {0} is not a library key".format(raw_value)) + + return result + + def handle(self, *args, **options): + """ + By convention set by django developers, this method actually executes command's actions. + So, there could be no better docstring than emphasize this once again. + """ + if len(args) == 0 and not options.get('all', False): + raise CommandError("reindex_library requires one or more arguments: ") + + store = modulestore() + + if options.get('all', False): + if query_yes_no( + "Reindexing all libraries might be a time consuming operation. Do you want to continue?", + default="no" + ): + library_keys = [library.location.library_key for library in store.get_libraries()] + else: + return + else: + library_keys = map(self._parse_library_key, args) + + for library_key in library_keys: + LibrarySearchIndexer.do_library_reindex(store, library_key)