diff --git a/django_minio_backend/models.py b/django_minio_backend/models.py index 8c5d533..53455a3 100644 --- a/django_minio_backend/models.py +++ b/django_minio_backend/models.py @@ -58,6 +58,7 @@ def __init__(self, self._REPLACE_EXISTING = kwargs.get('replace_existing', False) self.__CLIENT: Union[minio.Minio, None] = None + self.__CLIENT_EXTERNAL: Union[minio.Minio, None] = None self.__MINIO_ENDPOINT: str = get_setting("MINIO_ENDPOINT") self.__MINIO_EXTERNAL_ENDPOINT: str = get_setting("MINIO_EXTERNAL_ENDPOINT", self.__MINIO_ENDPOINT) self.__MINIO_ACCESS_KEY: str = get_setting("MINIO_ACCESS_KEY") @@ -190,12 +191,19 @@ def url(self, name: str): return f'{self.base_url_external}/{self._BUCKET_NAME}/{name}' try: - u: str = self.client.presigned_get_object( - bucket_name=self._BUCKET_NAME, - object_name=name.encode('utf-8'), - expires=get_setting("MINIO_URL_EXPIRY_HOURS", timedelta(days=7)) # Default is 7 days - ) - return u if self.same_endpoints else u.replace(self.base_url, self.base_url_external, 1) + if self.same_endpoints: + u: str = self.client.presigned_get_object( + bucket_name=self._BUCKET_NAME, + object_name=name.encode('utf-8'), + expires=get_setting("MINIO_URL_EXPIRY_HOURS", timedelta(days=7)) # Default is 7 days + ) + else: + u: str = self.client_external.presigned_get_object( + bucket_name=self._BUCKET_NAME, + object_name=name.encode('utf-8'), + expires=get_setting("MINIO_URL_EXPIRY_HOURS", timedelta(days=7)) # Default is 7 days + ) + return u except urllib3.exceptions.MaxRetryError: raise ConnectionError("Couldn't connect to Minio. Check django_minio_backend parameters in Django-Settings") @@ -279,6 +287,13 @@ def client(self) -> minio.Minio: return self.__CLIENT return self.__CLIENT + @property + def client_external(self) -> minio.Minio: + if not self.__CLIENT_EXTERNAL: + self.new_client(internal=False) + return self.__CLIENT_EXTERNAL + return self.__CLIENT_EXTERNAL + @property def base_url(self) -> str: return self.__BASE_URL @@ -287,10 +302,9 @@ def base_url(self) -> str: def base_url_external(self) -> str: return self.__BASE_URL_EXTERNAL - def new_client(self): + def new_client(self, internal: bool = True): """ - Instantiates a new Minio client and - :return: + Instantiates a new Minio client and assigns it to their respective class variable """ # Safety Guards if not self.PRIVATE_BUCKETS or not self.PUBLIC_BUCKETS: @@ -301,13 +315,16 @@ def new_client(self): ) mc = minio.Minio( - endpoint=self.__MINIO_ENDPOINT, + endpoint=self.__MINIO_ENDPOINT if internal else self.__MINIO_EXTERNAL_ENDPOINT, access_key=self.__MINIO_ACCESS_KEY, secret_key=self.__MINIO_SECRET_KEY, - secure=self.__MINIO_USE_HTTPS, + secure=self.__MINIO_USE_HTTPS if internal else self.__MINIO_EXTERNAL_ENDPOINT_USE_HTTPS, http_client=self.HTTP_CLIENT, ) - self.__CLIENT = mc + if internal: + self.__CLIENT = mc + else: + self.__CLIENT_EXTERNAL = mc # MAINTENANCE def check_bucket_existence(self):