from django.core.management.base import BaseCommand, CommandError from library import models from library.indexer import model_search, index_works, indexer FORMATTER = "{w.name:50s} {w.edition:15s} {w.collection.name:15s}" class Command(BaseCommand): help = "Imports works from a csv file" def add_arguments(self, parser): parser.add_argument("action", choices=("run", "search", "terms")) parser.add_argument("query", nargs="*") parser.add_argument("--collection", "-c", nargs="*", type=int) # parser.add_argument("collection", type=int, help="Collection ID") # parser.add_argument("source", type=argparse.FileType("r"), help="Source CSV") def handle(self, action, query, *args, **options): try: method = getattr(self, f"handle_{action}") except AttributeError: raise RuntimeError(f"Unknown handler: {action}") return method("".join(query), options["collection"] or []) def handle_run(self, query, collections=[]): index_works(models.Work.objects.all()) def handle_search(self, query, collections=[]): for result in model_search(query, collections): print(FORMATTER.format(w=result)) def handle_terms(self, query, collections=[]): ix = indexer.get_index() with ix.searcher() as searcher: print(b", ".join(searcher.lexicon(query or "text")))