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