Files
fondex-store-service/core/utils/storage.py
2026-03-26 14:06:37 +05:00

49 lines
1.8 KiB
Python

from typing import Optional, Union
from storages.backends.s3boto3 import S3Boto3Storage
from config.env import env
class CustomMediaStorage(S3Boto3Storage):
"""Media fayllar uchun nisbiy URL qaytaradigan storage."""
def url(self, name, parameters=None, expire=None, http_method=None):
# Name: products/img.png -> /resources/media/products/img.png
return f"/resources/media/{name}"
class CustomStaticStorage(S3Boto3Storage):
"""Static fayllar uchun nisbiy URL qaytaradigan storage."""
def url(self, name, parameters=None, expire=None, http_method=None):
return f"/resources/static/{name}"
class Storage:
storages = ["AWS", "MINIO", "FILE", "STATIC"]
def __init__(self, storage: Union[str], storage_type: Union[str] = "default") -> None:
self.storage = storage
self.sorage_type = storage_type
if storage not in self.storages:
raise ValueError(f"Invalid storage type: {storage}")
def get_backend(self) -> Optional[str]:
match self.storage:
case "AWS" | "MINIO":
if self.sorage_type == "default":
return "core.utils.storage.CustomMediaStorage"
return "core.utils.storage.CustomStaticStorage"
case "FILE":
return "django.core.files.storage.FileSystemStorage"
case "STATIC":
return "django.contrib.staticfiles.storage.StaticFilesStorage"
def get_options(self) -> Optional[dict]:
match self.storage:
case "AWS" | "MINIO":
if self.sorage_type == "default":
return {"bucket_name": env.str("STORAGE_BUCKET_MEDIA")}
elif self.sorage_type == "static":
return {"bucket_name": env.str("STORAGE_BUCKET_STATIC")}
case _:
return {}