Skip to content

Commit 4f1271e

Browse files
fix
Signed-off-by: Abhishek Kumar <[email protected]>
1 parent 5409e67 commit 4f1271e

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import os
2+
import uuid
3+
import json
4+
import minio
5+
import logging
6+
7+
8+
class storage:
9+
instance = None
10+
client = None
11+
12+
def __init__(self):
13+
try:
14+
"""
15+
Minio does not allow another way of configuring timeout for connection.
16+
The rest of configuration is copied from source code of Minio.
17+
"""
18+
import urllib3
19+
from datetime import timedelta
20+
21+
timeout = timedelta(seconds=1).seconds
22+
23+
mgr = urllib3.PoolManager(
24+
timeout=urllib3.util.Timeout(connect=timeout, read=timeout),
25+
maxsize=10,
26+
retries=urllib3.Retry(
27+
total=5, backoff_factor=0.2, status_forcelist=[500, 502, 503, 504]
28+
)
29+
)
30+
self.client = minio.Minio(
31+
os.getenv("MINIO_STORAGE_CONNECTION_URL"),
32+
access_key=os.getenv("MINIO_STORAGE_ACCESS_KEY"),
33+
secret_key=os.getenv("MINIO_STORAGE_SECRET_KEY"),
34+
secure=False,
35+
http_client=mgr
36+
)
37+
except Exception as e:
38+
logging.info(e)
39+
raise e
40+
41+
@staticmethod
42+
def unique_name(name):
43+
name, extension = os.path.splitext(name)
44+
return '{name}.{random}{extension}'.format(
45+
name=name,
46+
extension=extension,
47+
random=str(uuid.uuid4()).split('-')[0]
48+
)
49+
50+
51+
def upload(self, bucket, file, filepath):
52+
key_name = storage.unique_name(file)
53+
self.client.fput_object(bucket, key_name, filepath)
54+
return key_name
55+
56+
def download(self, bucket, file, filepath):
57+
self.client.fget_object(bucket, file, filepath)
58+
59+
def download_directory(self, bucket, prefix, path):
60+
objects = self.client.list_objects(bucket, prefix, recursive=True)
61+
for obj in objects:
62+
file_name = obj.object_name
63+
self.download(bucket, file_name, os.path.join(path, file_name))
64+
65+
def upload_stream(self, bucket, file, bytes_data):
66+
key_name = storage.unique_name(file)
67+
self.client.put_object(
68+
bucket, key_name, bytes_data, bytes_data.getbuffer().nbytes
69+
)
70+
return key_name
71+
72+
def download_stream(self, bucket, file):
73+
data = self.client.get_object(bucket, file)
74+
return data.read()
75+
76+
@staticmethod
77+
def get_instance():
78+
if storage.instance is None:
79+
storage.instance = storage()
80+
return storage.instance

0 commit comments

Comments
 (0)