Fixes
[redakcja.git] / src / catalogue / ebook_utils.py
1 # -*- coding: utf-8 -*-
2 from io import BytesIO
3 from catalogue.models import Book
4 from librarian import DocProvider
5 from django.http import HttpResponse
6
7
8 class RedakcjaDocProvider(DocProvider):
9     """Used for getting books' children."""
10
11     def __init__(self, publishable):
12         self.publishable = publishable
13
14     def by_slug(self, slug):
15         return BytesIO(Book.objects.get(dc_slug=slug
16                     ).materialize(publishable=self.publishable
17                     ).encode('utf-8'))
18
19
20 def serve_file(file_path, name, mime_type):
21     def read_chunks(f, size=8192):
22         chunk = f.read(size)
23         while chunk:
24             yield chunk
25             chunk = f.read(size)
26
27     response = HttpResponse(content_type=mime_type)
28     response['Content-Disposition'] = 'attachment; filename=%s' % name
29     with open(file_path, 'rb') as f:
30         for chunk in read_chunks(f):
31             response.write(chunk)
32     return response