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
52 print "Parsing '%s'" % file_path
59 book = Book.from_xml_file(file_path, overwrite=force)
62 if os.path.isfile(file_base + '.pdf'):
63 book.pdf_file.save('%s.pdf' % book.slug, File(file(file_base + '.pdf')))
65 print "Importing %s.pdf" % file_base
66 if os.path.isfile(file_base + '.odt'):
67 book.odt_file.save('%s.odt' % book.slug, File(file(file_base + '.odt')))
69 print "Importing %s.odt" % file_base
70 if os.path.isfile(file_base + '.txt'):
71 book.txt_file.save('%s.txt' % book.slug, File(file(file_base + '.txt')))
73 print "Importing %s.txt" % file_base
74 if os.path.isfile(file_base + '.mp3'):
75 book.mp3_file.save('%s.mp3' % book.slug, File(file(file_base + '.mp3')))
77 print "Importing %s.txt" % file_base
78 if os.path.isfile(file_base + '.ogg'):
79 book.ogg_file.save('%s.ogg' % book.slug, File(file(file_base + '.ogg')))
81 print "Importing %s.ogg" % file_base
85 except Book.AlreadyExists, msg:
86 print self.style.ERROR('%s: Book already imported. Skipping. To overwrite use --force.' %
92 print "Results: %d files imported, %d skipped, %d total." % (
93 files_imported, files_skipped, files_imported + files_skipped)
97 transaction.leave_transaction_management()