|
| 1 | +import typing as t |
| 2 | +import uuid |
| 3 | +import warnings |
| 4 | +from datetime import datetime |
| 5 | + |
| 6 | +from ellar.app import current_injector |
| 7 | +from ellar_storage import StorageService, StoredFile |
| 8 | +from sqlalchemy_file.file import File as BaseFile |
| 9 | + |
| 10 | +from ellar_sql.constant import DEFAULT_STORAGE_PLACEHOLDER |
| 11 | + |
| 12 | + |
| 13 | +class File(BaseFile): |
| 14 | + """Takes a file as content and uploads it to the appropriate storage |
| 15 | + according to the attached Column and file information into the |
| 16 | + database as JSON. |
| 17 | +
|
| 18 | + Default attributes provided for all ``File`` include: |
| 19 | +
|
| 20 | + Attributes: |
| 21 | + filename (str): This is the name of the uploaded file |
| 22 | + file_id: This is the generated UUID for the uploaded file |
| 23 | + upload_storage: Name of the storage used to save the uploaded file |
| 24 | + path: This is a combination of `upload_storage` and `file_id` separated by |
| 25 | + `/`. This will be use later to retrieve the file |
| 26 | + content_type: This is the content type of the uploaded file |
| 27 | + uploaded_at (datetime): This is the upload date in ISO format |
| 28 | + url (str): CDN url of the uploaded file |
| 29 | + file: Only available for saved content, internally call |
| 30 | + [StorageManager.get_file()][sqlalchemy_file.storage.StorageManager.get_file] |
| 31 | + on path and return an instance of `StoredFile` |
| 32 | + """ |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + content: t.Any = None, |
| 37 | + filename: t.Optional[str] = None, |
| 38 | + content_type: t.Optional[str] = None, |
| 39 | + content_path: t.Optional[str] = None, |
| 40 | + **kwargs: t.Dict[str, t.Any], |
| 41 | + ) -> None: |
| 42 | + super().__init__( |
| 43 | + content=content, |
| 44 | + filename=filename, |
| 45 | + content_path=content_path, |
| 46 | + content_type=content_type, |
| 47 | + **kwargs, |
| 48 | + ) |
| 49 | + |
| 50 | + def save_to_storage(self, upload_storage: t.Optional[str] = None) -> None: |
| 51 | + """Save current file into provided `upload_storage`.""" |
| 52 | + storage_service = current_injector.get(StorageService) |
| 53 | + valid_upload_storage = storage_service.get_container( |
| 54 | + upload_storage |
| 55 | + if not upload_storage == DEFAULT_STORAGE_PLACEHOLDER |
| 56 | + else None |
| 57 | + ).name |
| 58 | + |
| 59 | + extra = self.get("extra", {}) |
| 60 | + extra.update({"content_type": self.content_type}) |
| 61 | + |
| 62 | + metadata = self.get("metadata", None) |
| 63 | + if metadata is not None: |
| 64 | + warnings.warn( |
| 65 | + 'metadata attribute is deprecated. Use extra={"meta_data": ...} instead', |
| 66 | + DeprecationWarning, |
| 67 | + stacklevel=1, |
| 68 | + ) |
| 69 | + extra.update({"meta_data": metadata}) |
| 70 | + |
| 71 | + if extra.get("meta_data", None) is None: |
| 72 | + extra["meta_data"] = {} |
| 73 | + |
| 74 | + extra["meta_data"].update( |
| 75 | + {"filename": self.filename, "content_type": self.content_type} |
| 76 | + ) |
| 77 | + stored_file = self.store_content( |
| 78 | + self.original_content, |
| 79 | + valid_upload_storage, |
| 80 | + extra=extra, |
| 81 | + headers=self.get("headers", None), |
| 82 | + content_path=self.content_path, |
| 83 | + ) |
| 84 | + self["file_id"] = stored_file.name |
| 85 | + self["upload_storage"] = valid_upload_storage |
| 86 | + self["uploaded_at"] = datetime.utcnow().isoformat() |
| 87 | + self["path"] = f"{valid_upload_storage}/{stored_file.name}" |
| 88 | + self["url"] = stored_file.get_cdn_url() |
| 89 | + self["saved"] = True |
| 90 | + |
| 91 | + def store_content( # type:ignore[override] |
| 92 | + self, |
| 93 | + content: t.Any, |
| 94 | + upload_storage: t.Optional[str] = None, |
| 95 | + name: t.Optional[str] = None, |
| 96 | + metadata: t.Optional[t.Dict[str, t.Any]] = None, |
| 97 | + extra: t.Optional[t.Dict[str, t.Any]] = None, |
| 98 | + headers: t.Optional[t.Dict[str, str]] = None, |
| 99 | + content_path: t.Optional[str] = None, |
| 100 | + ) -> StoredFile: |
| 101 | + """Store content into provided `upload_storage` |
| 102 | + with additional `metadata`. Can be used by processors |
| 103 | + to store additional files. |
| 104 | + """ |
| 105 | + name = name or str(uuid.uuid4()) |
| 106 | + storage_service = current_injector.get(StorageService) |
| 107 | + |
| 108 | + stored_file = storage_service.save_content( |
| 109 | + name=name, |
| 110 | + content=content, |
| 111 | + upload_storage=upload_storage, |
| 112 | + metadata=metadata, |
| 113 | + extra=extra, |
| 114 | + headers=headers, |
| 115 | + content_path=content_path, |
| 116 | + ) |
| 117 | + self["files"].append(f"{upload_storage}/{name}") |
| 118 | + return stored_file |
| 119 | + |
| 120 | + @property |
| 121 | + def file(self) -> StoredFile: # type:ignore[override] |
| 122 | + if self.get("saved", False): |
| 123 | + storage_service = current_injector.get(StorageService) |
| 124 | + return storage_service.get(self["path"]) |
| 125 | + raise RuntimeError("Only available for saved file") |
0 commit comments