images in epub
[redakcja.git] / apps / dvcs / storage.py
1 from __future__ import unicode_literals
2
3 import os
4 from django.core.files.base import ContentFile, File
5 from django.core.files.storage import FileSystemStorage
6
7 try:
8     from gzip import compress, decompress
9 except ImportError:
10     # Python < 3.2
11     from gzip import GzipFile
12     from StringIO import StringIO
13
14     def compress(data):
15         compressed = StringIO()
16         GzipFile(fileobj=compressed, mode="wb").write(data)
17         return compressed.getvalue()
18
19     def decompress(data):
20         return GzipFile(fileobj=StringIO(data)).read()
21
22
23 class GzipFileSystemStorage(FileSystemStorage):
24     def _open(self, name, mode='rb'):
25         """TODO: This is good for reading; what about writing?"""
26         f = open(self.path(name), 'rb')
27         text = f.read()
28         f.close()
29         return ContentFile(decompress(text))
30
31     def _save(self, name, content):
32         content = ContentFile(compress(content.read()))
33         return super(GzipFileSystemStorage, self)._save(name, content)
34
35     def get_available_name(self, name):
36         if self.exists(name):
37             self.delete(name)
38         return name