|
| 1 | +import shutil |
| 2 | +from contextlib import suppress |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +from fastapi import FastAPI, Request |
| 6 | +from fastapi.staticfiles import StaticFiles |
| 7 | + |
| 8 | +from common.services.storage_services.base import StorageService |
| 9 | +from common.settings import get_settings |
| 10 | + |
| 11 | +settings = get_settings() |
| 12 | + |
| 13 | + |
| 14 | +class LocalStorageService(StorageService): |
| 15 | + name = "local" |
| 16 | + |
| 17 | + @classmethod |
| 18 | + async def upload(cls, key: str, path: Path) -> None: |
| 19 | + storage_path = Path(settings.LOCAL_STORAGE_PATH) / key |
| 20 | + shutil.copy2(path, storage_path) |
| 21 | + |
| 22 | + @classmethod |
| 23 | + async def download(cls, key: str, path: Path) -> None: |
| 24 | + storage_path = Path(settings.LOCAL_STORAGE_PATH) / key |
| 25 | + shutil.copy2(storage_path, path) |
| 26 | + |
| 27 | + @classmethod |
| 28 | + async def generate_presigned_url_put_object(cls, key: str, expiry_seconds: int) -> str: # noqa: ARG003 |
| 29 | + return f"/api/proxy/mock_storage/uploadfile/{key}" |
| 30 | + |
| 31 | + @classmethod |
| 32 | + async def generate_presigned_url_get_object(cls, key: str, filename: str, expiry_seconds: int) -> str: # noqa: ARG003 |
| 33 | + return f"/api/proxy/mock_storage/static/{key}" |
| 34 | + |
| 35 | + @classmethod |
| 36 | + async def check_object_exists(cls, key: str) -> bool: |
| 37 | + storage_path = Path(settings.LOCAL_STORAGE_PATH) / key |
| 38 | + return storage_path.exists() |
| 39 | + |
| 40 | + @classmethod |
| 41 | + async def delete(cls, key: str) -> None: |
| 42 | + with suppress(FileNotFoundError): |
| 43 | + storage_path = Path(settings.LOCAL_STORAGE_PATH) / key |
| 44 | + storage_path.unlink() |
| 45 | + |
| 46 | + |
| 47 | +mock_storage_app = FastAPI(title="Mock storage service") |
| 48 | + |
| 49 | +mock_storage_app.mount("/static", StaticFiles(directory=settings.LOCAL_STORAGE_PATH), name="static") |
| 50 | + |
| 51 | + |
| 52 | +@mock_storage_app.put("/uploadfile/{file_path:path}") |
| 53 | +async def upload_file_to_mock_storage(file_path: str, request: Request): |
| 54 | + storage_path = Path(settings.LOCAL_STORAGE_PATH) / file_path |
| 55 | + storage_path.parent.mkdir(parents=True, exist_ok=True) |
| 56 | + storage_path.write_bytes(await request.body()) |
0 commit comments