3 from optparse import make_option
5 from django.core.management.base import BaseCommand
6 from django.core.management.color import color_style
7 from django.core.files import File
9 from catalogue.models import Book
12 class Command(BaseCommand):
13 option_list = BaseCommand.option_list + (
14 make_option('-q', '--quiet', action='store_false', dest='verbose', default=True,
15 help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'),
16 make_option('-f', '--force', action='store_true', dest='force', default=False,
17 help='Print status messages to stdout')
19 help = 'Imports books from the specified directories.'
20 args = 'directory [directory ...]'
22 def handle(self, *directories, **options):
23 from django.db import transaction
25 self.style = color_style()
27 verbose = options.get('verbose')
28 force = options.get('force')
29 show_traceback = options.get('traceback', False)
31 # Start transaction management.
32 transaction.commit_unless_managed()
33 transaction.enter_transaction_management()
34 transaction.managed(True)
39 for dir_name in directories:
40 if not os.path.isdir(dir_name):
41 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)
53 print "Parsing '%s'" % file_path
60 book = Book.from_xml_file(file_path, overwrite=force)
63 if os.path.isfile(file_base + '.pdf'):
64 book.pdf_file.save('%s.pdf' % book.slug, File(file(file_base + '.pdf')))
66 print "Importing %s.pdf" % file_base
67 if os.path.isfile(file_base + '.odt'):
68 book.odt_file.save('%s.odt' % book.slug, File(file(file_base + '.odt')))
70 print "Importing %s.odt" % file_base
71 if os.path.isfile(file_base + '.txt'):
72 book.txt_file.save('%s.txt' % book.slug, File(file(file_base + '.txt')))
74 print "Importing %s.txt" % file_base
78 except Book.AlreadyExists, msg:
79 print self.style.ERROR('%s: Book already imported. Skipping. To overwrite use --force.' %
85 print "Results: %d files imported, %d skipped, %d total." % (
86 files_imported, files_skipped, files_imported + files_skipped)
90 transaction.leave_transaction_management()