1
1
import os
2
- from django_petra .path import base_path
3
2
import shutil
3
+ import mimetypes
4
+
5
+ from django_petra .path import base_path
4
6
5
7
class LocalStorage :
6
8
def __init__ (self ):
@@ -9,15 +11,19 @@ def __init__(self):
9
11
def get_full_path (self , path ):
10
12
return os .path .join (self .base_path , 'storage' , 'public' , path )
11
13
12
- def put (self , path , contents ):
14
+ def put (self , path , file ):
13
15
full_path = self .get_full_path (path )
16
+ file_content = file .read ()
14
17
os .makedirs (os .path .dirname (full_path ), exist_ok = True )
15
- with open (full_path , 'w' ) as file :
16
- file .write (contents )
18
+
19
+ # Check if contents is bytes or string
20
+ mode = 'wb' if isinstance (file_content , bytes ) else 'w'
21
+ with open (full_path , mode ) as file :
22
+ file .write (file_content )
17
23
18
24
def get (self , path ):
19
25
full_path = self .get_full_path (path )
20
- with open (full_path , 'r ' ) as file :
26
+ with open (full_path , 'rb ' ) as file :
21
27
return file .read ()
22
28
23
29
def delete (self , path ):
@@ -27,9 +33,9 @@ def delete(self, path):
27
33
except FileNotFoundError as e :
28
34
print (f"Error deleting local file: { e } " )
29
35
30
- def update (self , path , contents ):
36
+ def update (self , path , file ):
31
37
self .delete (path )
32
- self .put (path , contents )
38
+ self .put (path , file )
33
39
34
40
def exists (self , path ):
35
41
full_path = self .get_full_path (path )
@@ -93,3 +99,9 @@ def move(self, source, destination):
93
99
shutil .move (full_source_path , full_destination_path )
94
100
except Exception as e :
95
101
print (f"Error moving local file: { e } " )
102
+
103
+ def content_type (self , path ):
104
+ content_type , _ = mimetypes .guess_type (path )
105
+ if not content_type :
106
+ content_type = 'application/octet-stream'
107
+ return content_type
0 commit comments