7ff494f87c1b09b99310caab1c76367d187c1edc
[redakcja.git] / apps / catalogue / management / commands / import_lessons.py
1 # -*- coding: utf-8 -*-
2
3 from optparse import make_option
4 from lxml import etree
5 import os
6
7 from django.core.management.base import BaseCommand
8 from django.core.management.color import color_style
9 from django.db import transaction
10 from librarian import ParseError, ValidationError
11
12 from catalogue.models import Book
13
14
15 class Command(BaseCommand):
16     option_list = BaseCommand.option_list + (
17         make_option('-q', '--quiet', action='store_false', dest='verbose', default=True, help='Less output'),
18     )
19     help = 'Imports XML files.'
20     args = 'directory'
21
22     def handle(self, directory, *args, **options):
23
24         self.style = color_style()
25
26         verbose = options.get('verbose')
27
28         # Start transaction management.
29         transaction.commit_unless_managed()
30         transaction.enter_transaction_management()
31         transaction.managed(True)
32
33         book_count = 0
34         commit_args = {
35             "author_name": 'Platforma',
36             "description": 'Automatycznie zaimportowane',
37             "publishable": True,
38         }
39         for xml_filename in os.listdir(directory):
40             if verbose:
41                 print xml_filename
42             text = open(os.path.join(directory, xml_filename)).read().decode('utf-8')
43             try:
44                 tree = etree.fromstring(text)
45                 slug = xml_filename.split('.')[0]
46             except Exception as e:
47                 print xml_filename, 'error: ', repr(e)
48             else:
49                 title = tree.find('.//header').text
50                 print book_count, slug, title
51                 Book.create(
52                     text=text,
53                     creator=None,
54                     slug=slug,
55                     title=title,
56                     gallery=slug,
57                     commit_args=commit_args,
58                 )
59                 book_count += 1
60
61         # Print results
62         print
63         print "Results:"
64         print "Imported %d books" % book_count
65         print
66
67         transaction.commit()
68         transaction.leave_transaction_management()