From 5ceb970443b1ab2b0ffcf0328fdbff9969b666cb Mon Sep 17 00:00:00 2001 From: Maksym Shalenyi Date: Wed, 7 Aug 2024 14:27:23 -0700 Subject: [PATCH] Add support for complex file ids --- sqlalchemy_file/storage.py | 12 ++++++++---- tests/test_storage_manager.py | 12 ++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/sqlalchemy_file/storage.py b/sqlalchemy_file/storage.py index 95e66ce..dd93de7 100644 --- a/sqlalchemy_file/storage.py +++ b/sqlalchemy_file/storage.py @@ -127,7 +127,7 @@ def get_file(cls, path: str) -> StoredFile: The path is expected to be `storage_name/file_id`. """ upload_storage, file_id = cls._get_storage_and_file_id(path) - return StoredFile(StorageManager.get(upload_storage).get_object(file_id)) + return StoredFile(cls.get(upload_storage).get_object(file_id)) @classmethod def delete_file(cls, path: str) -> bool: @@ -136,7 +136,7 @@ def delete_file(cls, path: str) -> bool: The path is expected to be `storage_name/file_id`. """ upload_storage, file_id = cls._get_storage_and_file_id(path) - obj = StorageManager.get(upload_storage).get_object(file_id) + obj = cls.get(upload_storage).get_object(file_id) if obj.driver.name == LOCAL_STORAGE_DRIVER_NAME: """Try deleting associated metadata file""" with contextlib.suppress(ObjectDoesNotExistError): @@ -156,5 +156,9 @@ def _get_storage_and_file_id(cls, path: str) -> Tuple[str, str]: The path is expected to be `storage_name/file_id`. """ - path_parts = path.split("/") - return "/".join(path_parts[:-1]), path_parts[-1] + # first trying complex file_id + storage_name, file_id = path.split("/", 1) + if storage_name in cls._storages: + return storage_name, file_id + # the trying complex storage name + return tuple(path.rsplit("/", 1)) diff --git a/tests/test_storage_manager.py b/tests/test_storage_manager.py index 6fde04e..8f84e15 100644 --- a/tests/test_storage_manager.py +++ b/tests/test_storage_manager.py @@ -18,6 +18,18 @@ def test_get_storage_and_file_id(self) -> None: "file", ) + def test_get_storage_and_complex_file_id(self) -> None: + StorageManager.add_storage("storage", get_dummy_container("storage")) + + assert StorageManager._get_storage_and_file_id("storage/file") == ( + "storage", + "file", + ) + assert StorageManager._get_storage_and_file_id("storage/folder/file") == ( + "storage", + "folder/file", + ) + def test_first_configured_is_default(self) -> None: StorageManager.add_storage("first", get_dummy_container("first")) StorageManager.add_storage("second", get_dummy_container("second"))