This repository was archived by the owner on Sep 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathstorage_backends.py
More file actions
86 lines (60 loc) · 2.33 KB
/
storage_backends.py
File metadata and controls
86 lines (60 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# -*- coding: utf-8 -*-
import codecs
import os
from io import BytesIO
from thumbnails import helpers
from .conf import settings
class BaseStorageBackend(object):
def __init__(self):
self.location = settings.THUMBNAIL_PATH
def path(self, path):
"""
Creates a path based on the location attribute of the backend and the path argument
of the function. If the path argument is an absolute path the path is returned.
:param path: The path that should be joined with the backends location.
"""
if os.path.isabs(path):
return path
return os.path.join(self.location, path)
def open(self, name, **kwargs):
return self._open(self.path(name), **kwargs)
def exists(self, name):
return self._exists(self.path(name))
def save(self, name, data):
return self._save(self.path(name), data)
def _open(self, name, **kwargs):
raise NotImplementedError
def _exists(self, name):
raise NotImplementedError
def _save(self, name, data):
raise NotImplementedError
class FilesystemStorageBackend(BaseStorageBackend):
"""
A storage engine that uses Python built in filesystem functionality.
"""
def __init__(self):
super(FilesystemStorageBackend, self).__init__()
if not os.path.exists(self.location):
os.makedirs(self.location, exist_ok=True)
def _open(self, name, mode='rb', encoding=None, errors='strict'):
return codecs.open(name, mode=mode, encoding=encoding, errors=errors)
def _exists(self, name):
return os.path.exists(name)
def _save(self, name, data):
if not os.path.exists(os.path.dirname(name)):
os.makedirs(os.path.dirname(name), exist_ok=True)
with open(name, 'wb') as f:
f.write(data)
class DjangoStorageBackend(BaseStorageBackend):
"""
A wrapper around Django's storage backend
"""
def __init__(self):
super(DjangoStorageBackend, self).__init__()
self._backend = helpers.import_attribute(settings.DEFAULT_FILE_STORAGE)
def _open(self, name, mode='rb'):
return self._backend.open(name, mode=mode)
def _exists(self, name):
return self._backend.exists(name)
def _save(self, name, data):
return self._backend.save(name, BytesIO(data))