d1dac54e479f92a160caafb751afe89536a0b400
[wolnelektury.git] / apps / catalogue / management / commands / importbooks.py
1 import os
2
3 from django.core.management.base import BaseCommand
4 from django.core.management.color import color_style
5 from optparse import make_option
6
7 from catalogue.models import Book
8
9
10 class Command(BaseCommand):
11     option_list = BaseCommand.option_list + (
12         make_option('--verbosity', action='store', dest='verbosity', default='1',
13             type='choice', choices=['0', '1', '2'],
14             help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'),
15         make_option('--force', action='store_true', dest='force', default=False,
16             help='Overwrite previously imported files with the same id')
17     )
18     help = 'Imports books from the specified directories.'
19     args = 'directory [directory ...]'
20
21     def handle(self, *directories, **options):
22         from django.db import transaction
23
24         self.style = color_style()
25
26         verbosity = int(options.get('verbosity', 1))
27         force = options.get('force')
28         show_traceback = options.get('traceback', False)
29
30         # Start transaction management.
31         transaction.commit_unless_managed()
32         transaction.enter_transaction_management()
33         transaction.managed(True)
34
35         for dir_name in directories:
36             if not os.path.isdir(dir_name):
37                 print self.style.ERROR("Skipping '%s': not a directory." % dir_name)
38             else:
39                 for file_name in os.listdir(dir_name):
40                     file_path = os.path.join(dir_name, file_name)
41                     if not os.path.splitext(file_name)[1] == '.xml':
42                         print self.style.NOTICE("Skipping '%s': not an XML file." % file_path)
43                         continue
44                     if verbosity > 0:
45                         print "Parsing '%s'" % file_path
46                     
47                     Book.from_xml_file(file_path)
48         
49         transaction.commit()
50         transaction.leave_transaction_management()
51