Add update function for MinioService

This commit is contained in:
Tobias Eidelpes 2021-01-08 11:19:18 +01:00
parent bc82e3675d
commit 8371aba88b

View File

@ -10,16 +10,15 @@ from app_be.services.StorageServiceInterface import StorageServiceInterface
class MinioService(StorageServiceInterface): class MinioService(StorageServiceInterface):
name = "MinIO" name = "MinIO"
@staticmethod @staticmethod
def check() -> bool: def check() -> bool:
print("Checking MinIO availability") print("Checking MinIO availability")
try: try:
url= settings.AWS_HOST url = settings.AWS_HOST
r = requests.put(url) r = requests.put(url)
if not (r.status_code >= 200 and r.status_code < 500): if not (200 <= r.status_code < 500):
return False return False
except: except:
return False return False
@ -34,9 +33,9 @@ class MinioService(StorageServiceInterface):
:return: Whether file was successfully uploaded :return: Whether file was successfully uploaded
""" """
try: try:
url= settings.AWS_HOST + filename url = settings.AWS_HOST + filename
headers = {'Content-Type': 'binary/octet-stream'} headers = {'Content-Type': 'binary/octet-stream'}
r = requests.put(url,data=file,headers=headers) r = requests.put(url, data=file, headers=headers)
if r.status_code == 200: if r.status_code == 200:
print("Successfully uploaded a file!") print("Successfully uploaded a file!")
else: else:
@ -45,6 +44,30 @@ class MinioService(StorageServiceInterface):
return False return False
return True return True
@staticmethod
def update_file(filename: str, file: bytes) -> bool:
"""Update a file on the minio storage.
Finds the latest version of the current file and adds another
version to the storage.
:param filename: The filename without the version.
:param file: Byte representation of the file to save as new version
:return True if successful, False otherwise
"""
try:
headers = {'Content-Type': 'binary/octet-stream'}
i = 0
while MinioService.read_file(filename + '_' + str(i)) is not False:
i = i + 1
url = settings.AWS_HOST + filename + '_' + str(i)
r = requests.put(url, data=file, headers=headers)
if r.status_code == 200:
print("Successfully uploaded a new version with identifier %s!".format(filename + '_' + str(i)))
else:
print("Something went wrong while updating")
except:
return False
return True
@staticmethod @staticmethod
def read_file(filename: str) -> bytes: def read_file(filename: str) -> bytes:
@ -57,7 +80,7 @@ class MinioService(StorageServiceInterface):
try: try:
url = settings.AWS_HOST + filename url = settings.AWS_HOST + filename
response = requests.get(url, stream=True) response = requests.get(url, stream=True)
file_bytes=response.content file_bytes = response.content
except: except:
print("Error downloading file from minio") print("Error downloading file from minio")
return file_bytes return file_bytes