From 75ceea22e23bb07bcc44d8209de64c74e07e1480 Mon Sep 17 00:00:00 2001 From: pamfilos Date: Thu, 25 Apr 2024 13:42:06 +0200 Subject: [PATCH] articles: files - cleans path from bucket and base dir Signed-off-by: pamfilos --- scoap3/tasks.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/scoap3/tasks.py b/scoap3/tasks.py index f1ee987e5..ea8c810e2 100644 --- a/scoap3/tasks.py +++ b/scoap3/tasks.py @@ -6,7 +6,7 @@ import pycountry from django.core.exceptions import MultipleObjectsReturned, ValidationError -from django.core.files.storage import storages +from django.core.files.storage import storages, default_storage from django.core.validators import URLValidator from elasticsearch import ConnectionError, ConnectionTimeout, Elasticsearch from sentry_sdk import capture_exception @@ -28,6 +28,18 @@ logger = logging.getLogger(__name__) +def get_default_storage_path(): + if hasattr(default_storage, "bucket"): + bucket_name = default_storage.bucket.name + media_path = default_storage.location + return f"{bucket_name}/{media_path}" + + return "" + + +DEFAULT_STORAGE_PATH = get_default_storage_path() + + def _rename_keys(data, replacements): for item in data: for old_key, new_key in replacements: @@ -113,7 +125,8 @@ def _create_article_file(data, article): for file in data.get("files", {}): article_id = article.id file_path = data["files"][file] - file_path = file_path.split("/", 1)[1] if "/" in file_path else file_path + if DEFAULT_STORAGE_PATH: + file_path = file_path.replace(DEFAULT_STORAGE_PATH, "") article = Article.objects.get(pk=article_id) article_file_data = {"article_id": article, "file": file_path} ArticleFile.objects.get_or_create(**article_file_data)