summaryrefslogtreecommitdiff
path: root/fbin/file_storage/filesystem.py
diff options
context:
space:
mode:
authorJon Bergli Heier <snakebite@jvnv.net>2019-07-24 09:02:43 +0200
committerJon Bergli Heier <snakebite@jvnv.net>2019-07-24 09:05:09 +0200
commitb72ecc321c315bafe40cc7406e87e088564ab8a9 (patch)
tree98d492c626fefdaacf1cc57db7a055fc28bf12e5 /fbin/file_storage/filesystem.py
parent86a34a0cccd79311c89ee1f3eacbff4f97d97e1f (diff)
Add file storage modules
Allows for storing files other places than the local file system. Currently the local filesystem and S3 are supported.
Diffstat (limited to 'fbin/file_storage/filesystem.py')
-rw-r--r--fbin/file_storage/filesystem.py44
1 files changed, 44 insertions, 0 deletions
diff --git a/fbin/file_storage/filesystem.py b/fbin/file_storage/filesystem.py
new file mode 100644
index 0000000..3433baf
--- /dev/null
+++ b/fbin/file_storage/filesystem.py
@@ -0,0 +1,44 @@
+import contextlib
+import os
+import tempfile
+
+from .base import BaseStorage
+
+class Storage(BaseStorage):
+ def __init__(self, app):
+ super().__init__(app)
+ os.makedirs(self.app.config['FILE_DIRECTORY'], exist_ok=True)
+
+ def store_file(self, uploaded_file, file_hash, user, ip):
+ size = uploaded_file.content_length
+ if hasattr(uploaded_file.stream, 'file'):
+ temp = None
+ temp_path = uploaded_file.stream.name
+ else:
+ temp = tempfile.NamedTemporaryFile(prefix='upload_', dir=self.app.config['FILE_DIRECTORY'], delete=False)
+ uploaded_file.save(temp.file)
+ temp_path = temp.name
+ size = os.path.getsize(temp_path)
+ try:
+ new_file = self.add_file(file_hash, uploaded_file.filename, size, user, ip)
+ os.rename(temp_path, new_file.get_path())
+ return new_file
+ except:
+ os.unlink(temp.name)
+ raise
+
+ def get_file(self, f):
+ path = f.get_path()
+ if not os.path.exists(path):
+ return
+ return path
+
+ def delete_file(self, f):
+ path = f.get_path()
+ if os.path.exists(path):
+ os.unlink(path)
+
+ @contextlib.contextmanager
+ def temp_file(self, f):
+ with open(f.get_path(), 'rb') as f:
+ yield f