Skip to content

File Storage on Azure Storage

Bases: StorageEngine

Source code in reportconnectors/file_storage/engine/azure_storage.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
class AzureStorageEngine(StorageEngine):
    def __init__(self, connection_string: str, **kwargs):
        self.blob_service: BlobServiceClient = BlobServiceClient.from_connection_string(conn_str=connection_string)
        self._kwargs = kwargs

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}({self.blob_service.url})"

    def create_container(self, container_name: str, **kwargs) -> Optional[bool]:
        max_tries = kwargs.get("max_tries", 8)
        wait_until_created = kwargs.get("wait_until_created", False)

        container_client = self.blob_service.get_container_client(container=container_name)
        if container_client.exists():
            return None
        # Container can be created only there is no other container with the same name being deleted at the moment
        # and that is why we catch the ResourceExistsError
        for i in range(max_tries):
            try:
                container_client.create_container()
                # It's not guaranteed for the container to be operational immediately after
                # container_client.create_container() is called.
                # Therefore, if we want to wait_until_created we need to check if container exists
                # and raise ResourceNotFoundError if it's not.
                if wait_until_created and not container_client.exists():
                    raise ResourceNotFoundError()
                break
            except (ResourceExistsError, ResourceNotFoundError):
                # Both Exceptions will trigger sleep with backoff time
                sleep_time = 2**i
                log.debug(f"Waiting for container to be created. {sleep_time=}, try={i+1}/{max_tries}")
                time.sleep(sleep_time)
        return True

    def remove_container(self, container_name: str, include_files: bool = True, **kwargs) -> Optional[bool]:
        container_client = self.blob_service.get_container_client(container=container_name)
        if container_client.exists() and (include_files or not list(container_client.list_blobs())):
            container_client.delete_container()
            return True
        return None

    def exists(self, container_name: str, file_name: Optional[str] = None) -> bool:
        if file_name is None:
            container_client = self.blob_service.get_container_client(container=container_name)
            return container_client.exists()
        blob_client = self.blob_service.get_blob_client(container=container_name, blob=file_name)
        return blob_client.exists()

    def get_file_link(self, file_name: str, container_name: str, **kwargs) -> Optional[str]:
        expiry_in: int = kwargs.get("expiry_in", 300)
        expiry_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=expiry_in)

        blob_client = self.blob_service.get_blob_client(container=container_name, blob=file_name)
        if not blob_client.exists():
            log.debug(self._missing_text(container_name=container_name, file_name=file_name))
            return None

        sas = generate_blob_sas(
            account_name=str(self.blob_service.account_name),
            account_key=self.blob_service.credential.account_key,
            container_name=blob_client.container_name,  # type: ignore [attr-defined]
            blob_name=blob_client.blob_name,  # type: ignore [attr-defined]
            permission=BlobSasPermissions(read=True),
            expiry=expiry_at,
        )
        file_url = f"{blob_client.url}?{sas}"
        return file_url

    def list_files(self, container_name: str, **kwargs) -> List[StorageFile]:
        include = "metadata"
        prefix = kwargs.get("prefix")
        container_client = self.blob_service.get_container_client(container=container_name)
        if not container_client.exists():
            log.debug(self._missing_text(container_name=container_name))
            return []

        blob_list = container_client.list_blobs(include=include, name_starts_with=prefix)
        files = []
        for blob in blob_list:
            _file = self._blob_element_to_file(blob=blob)
            files.append(_file)
        return files

    def filter_files(self, container_name: str, tags: Dict) -> List[StorageFile]:
        container_client = self.blob_service.get_container_client(container=container_name)
        if not container_client.exists():
            log.debug(self._missing_text(container_name=container_name))
            return []

        blob_list = container_client.find_blobs_by_tags(self._build_filter_expression_from_tags(tags))
        files = []
        for blob in blob_list:
            _file = StorageFile(name=blob.name)
            files.append(_file)
        return files

    def add_file(
        self, file: StorageFile, container_name: str, overwrite: bool = False, create_container: bool = True, **kwargs
    ) -> Optional[bool]:
        if create_container and not self.exists(container_name=container_name):
            self.create_container(container_name=container_name)

        blob_client = self.blob_service.get_blob_client(container=container_name, blob=file.name)
        if not overwrite and blob_client.exists():
            log.debug(
                f"File already exist. File: {container_name}/{file.name}. "
                "If you want to overwrite it, use `overwrite=True`"
            )
            return None
        if file.content is None:
            log.debug(f"No content found in file {file.name}. Nothing to upload.")
            return False
        blob_client.upload_blob(
            data=file.content,  # type: ignore
            metadata=self._prepare_metadata_to_save(file.metadata),
            overwrite=overwrite,
            content_settings=ContentSettings(content_type=file.content_type),
        )
        return True

    def get_file(
        self,
        file_name: str,
        container_name: str,
        include_content: bool = True,
        include_metadata: bool = True,
        **kwargs,
    ) -> Optional[StorageFile]:
        blob_client = self.blob_service.get_blob_client(container=container_name, blob=file_name)
        if not blob_client.exists():
            log.debug(self._missing_text(container_name=container_name, file_name=file_name))
            return None

        if include_content:
            blob_stream = blob_client.download_blob()
            metadata = blob_client.get_blob_properties().metadata if include_metadata else {}
            properties = blob_stream.properties
            content = blob_stream.readall()
            if isinstance(content, str):
                content = content.encode(encoding=self._encoding)
        else:
            properties = blob_client.get_blob_properties()
            metadata = properties.metadata if include_metadata else {}
            content = None

        _file = StorageFile(
            name=blob_client.blob_name,  # type: ignore [attr-defined]
            properties=self._get_blob_properties(properties),
            metadata=self._parse_metadata_from_storage(metadata),
            content=content,
            content_type=properties.content_settings.content_type,
        )
        return _file

    def delete_file(self, file_name: str, container_name: str, **kwargs) -> Optional[bool]:
        blob_client = self.blob_service.get_blob_client(container=container_name, blob=file_name)
        if not blob_client.exists():
            log.debug(self._missing_text(container_name=container_name, file_name=file_name))
            return None
        blob_client.delete_blob()
        return True

    def _blob_element_to_file(self, blob: BlobProperties) -> StorageFile:
        blob_metadata = getattr(blob, "metadata")
        parsed_properties = self._get_blob_properties(blob)
        parsed_metadata = self._parse_metadata_from_storage(metadata=blob_metadata)
        _file = StorageFile(
            name=blob.name,
            properties=parsed_properties,
            metadata=parsed_metadata,
            content_type=blob.content_settings.content_type,
        )
        return _file

    @staticmethod
    def _get_blob_properties(blob: BlobProperties) -> FileProperties:
        properties = FileProperties(last_modified=to_py_time(blob.last_modified), etag=blob.etag, size=blob.size)
        return properties

    @classmethod
    def _prepare_metadata_to_save(cls, metadata: Optional[Dict]) -> Dict:
        """
        Converts provided metadata to format accepted by Blob Storage SDK.
        This includes following rules:
        Keys: ASCII String without empty characters
        Values: ASCII String stripped

        Because things like blob names often have non-ascii characters, values with them are base64 encoded
        and the corresponding key is prefixed by "b64_"
        Encoding is then supported by _parse_metadata_from_storage() method
        eg. {"Asset Name": "żółć", "asset id": 1234} -> {"asset_id": "1234", "b64_asset_name": "xbzDs8WCxIc="}
        :param metadata: dictionary with metadata to save.
        :return: sanitized dictionary with metadata
        """

        new_metadata: Dict[str, str] = {}
        if metadata is None:
            return new_metadata
        for key, value in metadata.items():
            try:
                new_key = str(key).strip().casefold().replace(" ", "_")
                new_value = str(value).strip()
                # skip non-ascii keys
                if not new_key or not new_key.isascii():
                    continue
                # encode non-ascii values
                if not new_value.isascii():
                    new_key = f"{cls._b64_prefix}{new_key}"
                    new_value = base64.b64encode(new_value.encode(cls._encoding)).decode(cls._encoding)
                new_metadata[new_key] = new_value
            except (ValueError, TypeError):
                continue

        return new_metadata

    @classmethod
    def _parse_metadata_from_storage(cls, metadata: Dict) -> Dict:
        """
        Parses metadata received from Blob Storage.
        Because some data might be encoded with b64 this method scan the keys that are prefixed with b64_ prefix,
        decodes values for those keys and updates the key names.

        eg. {"asset_id": "1234", "b64_asset_name": "xbzDs8WCxIc="} -> {"asset_name": "żółć", "asset_id": "1234"}
        :param metadata: dictionary with metadata to read.
        :return: sanitized dictionary with metadata
        """
        if not metadata:
            return {}
        new_metadata = {}
        for key, value in metadata.items():
            if isinstance(key, str) and key.startswith(cls._b64_prefix):
                new_key = key[len(cls._b64_prefix) :]  # remove the prefix
                new_value = base64.b64decode(value).decode(cls._encoding)  # decode the value
                new_metadata[new_key] = new_value
            else:
                new_metadata[key] = value
        return new_metadata

    @staticmethod
    def _build_filter_expression_from_tags(tags: Dict) -> str:
        expression = " and ".join(f"\"{k}\"='{v}'" for k, v in tags.items())
        return expression