1 # -*- coding: utf-8 -*-
3 from collections import defaultdict
5 from urllib.request import urlopen
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.dcparser import BookInfo
11 from librarian import ParseError, ValidationError
13 from catalogue.models import Book
16 WL_API = 'http://www.wolnelektury.pl/api/books/'
19 class Command(BaseCommand):
20 help = 'Imports XML files from WL.'
22 def add_arguments(self, parser):
23 parser.add_argument('-q', '--quiet', action='store_false', dest='verbose', default=True,
26 def handle(self, *args, **options):
28 self.style = color_style()
30 verbose = options.get('verbose')
32 # Start transaction management.
33 transaction.enter_transaction_management()
36 print('Reading currently managed files (skipping hidden ones).')
37 slugs = defaultdict(list)
38 for b in Book.objects.exclude(slug__startswith='.').all():
41 text = b.materialize().encode('utf-8')
43 info = BookInfo.from_bytes(text)
44 except (ParseError, ValidationError):
47 slugs[info.slug].append(b)
51 "author_name": 'Platforma',
52 "description": 'Automatycznie zaimportowane z Wolnych Lektur',
57 print('Opening books list')
58 for book in json.load(urlopen(WL_API)):
59 book_detail = json.load(urlopen(book['href']))
60 xml_text = urlopen(book_detail['xml']).read()
61 info = BookInfo.from_bytes(xml_text)
62 previous_books = slugs.get(info.slug)
64 if len(previous_books) > 1:
65 print(self.style.ERROR("There is more than one book "
66 "with slug %s:") % info.slug)
67 previous_book = previous_books[0]
68 comm = previous_book.slug
72 print(book_count, info.slug , '-->', comm)
73 Book.import_xml_text(xml_text, title=info.title[:255],
74 slug=info.slug[:128], previous_book=previous_book,
75 commit_args=commit_args)
81 print("Imported %d books from WL:" % (
87 transaction.leave_transaction_management()