summaryrefslogtreecommitdiff
path: root/compressor/storage.py
diff options
context:
space:
mode:
Diffstat (limited to 'compressor/storage.py')
-rw-r--r--compressor/storage.py34
1 files changed, 26 insertions, 8 deletions
diff --git a/compressor/storage.py b/compressor/storage.py
index be9b066..16419a8 100644
--- a/compressor/storage.py
+++ b/compressor/storage.py
@@ -1,7 +1,9 @@
+from __future__ import unicode_literals
import errno
import gzip
-from os import path
+import os
from datetime import datetime
+import time
from django.core.files.storage import FileSystemStorage, get_storage_class
from django.utils.functional import LazyObject, SimpleLazyObject
@@ -26,13 +28,13 @@ class CompressorFileStorage(FileSystemStorage):
*args, **kwargs)
def accessed_time(self, name):
- return datetime.fromtimestamp(path.getatime(self.path(name)))
+ return datetime.fromtimestamp(os.path.getatime(self.path(name)))
def created_time(self, name):
- return datetime.fromtimestamp(path.getctime(self.path(name)))
+ return datetime.fromtimestamp(os.path.getctime(self.path(name)))
def modified_time(self, name):
- return datetime.fromtimestamp(path.getmtime(self.path(name)))
+ return datetime.fromtimestamp(os.path.getmtime(self.path(name)))
def get_available_name(self, name):
"""
@@ -49,7 +51,7 @@ class CompressorFileStorage(FileSystemStorage):
"""
try:
super(CompressorFileStorage, self).delete(name)
- except OSError, e:
+ except OSError as e:
if e.errno != errno.ENOENT:
raise
@@ -65,9 +67,25 @@ class GzipCompressorFileStorage(CompressorFileStorage):
"""
def save(self, filename, content):
filename = super(GzipCompressorFileStorage, self).save(filename, content)
- out = gzip.open(u'%s.gz' % self.path(filename), 'wb')
- out.writelines(open(self.path(filename), 'rb'))
- out.close()
+ orig_path = self.path(filename)
+ compressed_path = '%s.gz' % orig_path
+
+ f_in = open(orig_path, 'rb')
+ f_out = open(compressed_path, 'wb')
+ try:
+ f_out = gzip.GzipFile(fileobj=f_out)
+ f_out.write(f_in.read())
+ finally:
+ f_out.close()
+ f_in.close()
+ # Ensure the file timestamps match.
+ # os.stat() returns nanosecond resolution on Linux, but os.utime()
+ # only sets microsecond resolution. Set times on both files to
+ # ensure they are equal.
+ stamp = time.time()
+ os.utime(orig_path, (stamp, stamp))
+ os.utime(compressed_path, (stamp, stamp))
+
return filename