4 from django.core.management.base import BaseCommand
5 from django.core.management.color import color_style
6 from optparse import make_option
8 from catalogue.models import Book
11 class Command(BaseCommand):
12 option_list = BaseCommand.option_list + (
13 make_option('-q', '--quiet', action='store_false', dest='verbose', default=True,
14 help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'),
15 make_option('-f', '--force', action='store_true', dest='force', default=False,
16 help='Print status messages to stdout')
18 help = 'Imports books from the specified directories.'
19 args = 'directory [directory ...]'
21 def handle(self, *directories, **options):
22 from django.db import transaction
24 self.style = color_style()
26 verbose = options.get('verbose')
27 force = options.get('force')
28 show_traceback = options.get('traceback', False)
30 # Start transaction management.
31 transaction.commit_unless_managed()
32 transaction.enter_transaction_management()
33 transaction.managed(True)
38 for dir_name in directories:
39 if not os.path.isdir(dir_name):
40 print self.style.ERROR("%s: Not a directory. Skipping." % dir_name)
43 for file_name in os.listdir(dir_name):
44 file_path = os.path.join(dir_name, file_name)
45 file_base, ext = os.path.splitext(file_path)
47 # Skip files that are not XML files
49 print self.style.NOTICE("%s: Not an XML file. Skipping." % file_path)
54 print "Parsing '%s'" % file_path
61 book = Book.from_xml_file(file_path, overwrite=force)
64 if os.path.isfile(file_base + '.pdf'):
65 book.pdf_file.save('%s.pdf' % book.slug, File(file(file_base + '.pdf')))
67 print "Importing %s.pdf" % file_base
68 if os.path.isfile(file_base + '.odt'):
69 book.odt_file.save('%s.odt' % book.slug, File(file(file_base + '.odt')))
71 print "Importing %s.odt" % file_base
72 if os.path.isfile(file_base + '.txt'):
73 book.txt_file.save('%s.txt' % book.slug, File(file(file_base + '.txt')))
75 print "Importing %s.txt" % file_base
79 except Book.AlreadyExists, msg:
80 print self.style.ERROR('%s: Book already imported. Skipping. To overwrite use --force.' %
86 print "Results: %d files imported, %d skipped, %d total." % (
87 files_imported, files_skipped, files_imported + files_skipped)
91 transaction.leave_transaction_management()