-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
_container_client.py
1821 lines (1649 loc) · 93.5 KB
/
_container_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: disable=too-many-lines, docstring-keyword-should-match-keyword-only
import functools
import warnings
from typing import (
Any, AnyStr, Dict, List, IO, Iterable, Iterator, Optional, overload, Union,
TYPE_CHECKING
)
from urllib.parse import urlparse, quote, unquote
from typing_extensions import Self
from azure.core import MatchConditions
from azure.core.exceptions import HttpResponseError, ResourceNotFoundError
from azure.core.paging import ItemPaged
from azure.core.pipeline import Pipeline
from azure.core.pipeline.transport import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from ._shared.base_client import StorageAccountHostsMixin, TransportWrapper, parse_connection_str, parse_query
from ._shared.request_handlers import add_metadata_headers, serialize_iso
from ._shared.response_handlers import (
process_storage_error,
return_response_headers,
return_headers_and_deserialized
)
from ._generated import AzureBlobStorage
from ._generated.models import SignedIdentifier
from ._blob_client import BlobClient
from ._deserialize import deserialize_container_properties
from ._download import StorageStreamDownloader
from ._encryption import StorageEncryptionMixin
from ._lease import BlobLeaseClient
from ._list_blobs_helper import (
BlobNamesPaged,
BlobPrefix,
BlobPropertiesPaged,
FilteredBlobPaged,
IgnoreListBlobsDeserializer
)
from ._models import (
ContainerProperties,
BlobProperties,
BlobType,
FilteredBlob
)
from ._serialize import get_modify_conditions, get_container_cpk_scope_info, get_api_version, get_access_conditions
if TYPE_CHECKING:
from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential, TokenCredential
from azure.core.pipeline.transport import HttpResponse # pylint: disable=C4756
from datetime import datetime
from ._models import ( # pylint: disable=unused-import
PublicAccess,
AccessPolicy,
StandardBlobTier,
PremiumPageBlobTier)
def _get_blob_name(blob):
"""Return the blob name.
:param blob: A blob string or BlobProperties
:type blob: str or BlobProperties
:returns: The name of the blob.
:rtype: str
"""
try:
return blob.get('name')
except AttributeError:
return blob
class ContainerClient(StorageAccountHostsMixin, StorageEncryptionMixin): # pylint: disable=too-many-public-methods
"""A client to interact with a specific container, although that container
may not yet exist.
For operations relating to a specific blob within this container, a blob client can be
retrieved using the :func:`~get_blob_client` function.
For more optional configuration, please click
`here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#optional-configuration>`_.
:param str account_url:
The URI to the storage account. In order to create a client given the full URI to the container,
use the :func:`from_container_url` classmethod.
:param container_name:
The name of the container for the blob.
:type container_name: str
:param credential:
The credentials with which to authenticate. This is optional if the
account URL already has a SAS token. The value can be a SAS token string,
an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials,
an account shared access key, or an instance of a TokenCredentials class from azure.identity.
If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential
- except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError.
If using an instance of AzureNamedKeyCredential, "name" should be the storage account name, and "key"
should be the storage account key.
:keyword str api_version:
The Storage API version to use for requests. Default value is the most recent service version that is
compatible with the current SDK. Setting to an older version may result in reduced feature compatibility.
.. versionadded:: 12.2.0
:keyword str secondary_hostname:
The hostname of the secondary endpoint.
:keyword int max_block_size: The maximum chunk size for uploading a block blob in chunks.
Defaults to 4*1024*1024, or 4MB.
:keyword int max_single_put_size: If the blob size is less than or equal max_single_put_size, then the blob will be
uploaded with only one http PUT request. If the blob size is larger than max_single_put_size,
the blob will be uploaded in chunks. Defaults to 64*1024*1024, or 64MB.
:keyword int min_large_block_upload_threshold: The minimum chunk size required to use the memory efficient
algorithm when uploading a block blob. Defaults to 4*1024*1024+1.
:keyword bool use_byte_buffer: Use a byte buffer for block blob uploads. Defaults to False.
:keyword int max_page_size: The maximum chunk size for uploading a page blob. Defaults to 4*1024*1024, or 4MB.
:keyword int max_single_get_size: The maximum size for a blob to be downloaded in a single call,
the exceeded part will be downloaded in chunks (could be parallel). Defaults to 32*1024*1024, or 32MB.
:keyword int max_chunk_get_size: The maximum chunk size used for downloading a blob. Defaults to 4*1024*1024,
or 4MB.
:keyword str audience: The audience to use when requesting tokens for Azure Active Directory
authentication. Only has an effect when credential is of type TokenCredential. The value could be
https://storage.azure.com/ (default) or https://<account>.blob.core.windows.net.
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_containers.py
:start-after: [START create_container_client_from_service]
:end-before: [END create_container_client_from_service]
:language: python
:dedent: 8
:caption: Get a ContainerClient from an existing BlobServiceClient.
.. literalinclude:: ../samples/blob_samples_containers.py
:start-after: [START create_container_client_sasurl]
:end-before: [END create_container_client_sasurl]
:language: python
:dedent: 8
:caption: Creating the container client directly.
"""
def __init__(
self, account_url: str,
container_name: str,
credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long
**kwargs: Any
) -> None:
try:
if not account_url.lower().startswith('http'):
account_url = "https://" + account_url
except AttributeError as exc:
raise ValueError("Container URL must be a string.") from exc
parsed_url = urlparse(account_url.rstrip('/'))
if not container_name:
raise ValueError("Please specify a container name.")
if not parsed_url.netloc:
raise ValueError(f"Invalid URL: {account_url}")
_, sas_token = parse_query(parsed_url.query)
self.container_name = container_name
# This parameter is used for the hierarchy traversal. Give precedence to credential.
self._raw_credential = credential if credential else sas_token
self._query_str, credential = self._format_query_string(sas_token, credential)
super(ContainerClient, self).__init__(parsed_url, service='blob', credential=credential, **kwargs)
self._api_version = get_api_version(kwargs)
self._client = self._build_generated_client()
self._configure_encryption(kwargs)
def _build_generated_client(self):
client = AzureBlobStorage(self.url, base_url=self.url, pipeline=self._pipeline)
client._config.version = self._api_version # pylint: disable=protected-access
return client
def _format_url(self, hostname):
container_name = self.container_name
if isinstance(container_name, str):
container_name = container_name.encode('UTF-8')
return f"{self.scheme}://{hostname}/{quote(container_name)}{self._query_str}"
@classmethod
def from_container_url(
cls, container_url: str,
credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long
**kwargs: Any
) -> Self:
"""Create ContainerClient from a container url.
:param str container_url:
The full endpoint URL to the Container, including SAS token if used. This could be
either the primary endpoint, or the secondary endpoint depending on the current `location_mode`.
:type container_url: str
:param credential:
The credentials with which to authenticate. This is optional if the
account URL already has a SAS token, or the connection string already has shared
access key values. The value can be a SAS token string,
an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials,
an account shared access key, or an instance of a TokenCredentials class from azure.identity.
If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential
- except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError.
If using an instance of AzureNamedKeyCredential, "name" should be the storage account name, and "key"
should be the storage account key.
:type credential:
~azure.core.credentials.AzureNamedKeyCredential or
~azure.core.credentials.AzureSasCredential or
~azure.core.credentials.TokenCredential or
str or dict[str, str] or None
:keyword str audience: The audience to use when requesting tokens for Azure Active Directory
authentication. Only has an effect when credential is of type TokenCredential. The value could be
https://storage.azure.com/ (default) or https://<account>.blob.core.windows.net.
:returns: A container client.
:rtype: ~azure.storage.blob.ContainerClient
"""
try:
if not container_url.lower().startswith('http'):
container_url = "https://" + container_url
except AttributeError as exc:
raise ValueError("Container URL must be a string.") from exc
parsed_url = urlparse(container_url)
if not parsed_url.netloc:
raise ValueError(f"Invalid URL: {container_url}")
container_path = parsed_url.path.strip('/').split('/')
account_path = ""
if len(container_path) > 1:
account_path = "/" + "/".join(container_path[:-1])
account_url = f"{parsed_url.scheme}://{parsed_url.netloc.rstrip('/')}{account_path}?{parsed_url.query}"
container_name = unquote(container_path[-1])
if not container_name:
raise ValueError("Invalid URL. Please provide a URL with a valid container name")
return cls(account_url, container_name=container_name, credential=credential, **kwargs)
@classmethod
def from_connection_string(
cls, conn_str: str,
container_name: str,
credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long
**kwargs: Any
) -> Self:
"""Create ContainerClient from a Connection String.
:param str conn_str:
A connection string to an Azure Storage account.
:param container_name:
The container name for the blob.
:type container_name: str
:param credential:
The credentials with which to authenticate. This is optional if the
account URL already has a SAS token, or the connection string already has shared
access key values. The value can be a SAS token string,
an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials,
an account shared access key, or an instance of a TokenCredentials class from azure.identity.
Credentials provided here will take precedence over those in the connection string.
If using an instance of AzureNamedKeyCredential, "name" should be the storage account name, and "key"
should be the storage account key.
:type credential:
~azure.core.credentials.AzureNamedKeyCredential or
~azure.core.credentials.AzureSasCredential or
~azure.core.credentials.TokenCredential or
str or dict[str, str] or None
:keyword str audience: The audience to use when requesting tokens for Azure Active Directory
authentication. Only has an effect when credential is of type TokenCredential. The value could be
https://storage.azure.com/ (default) or https://<account>.blob.core.windows.net.
:returns: A container client.
:rtype: ~azure.storage.blob.ContainerClient
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_authentication.py
:start-after: [START auth_from_connection_string_container]
:end-before: [END auth_from_connection_string_container]
:language: python
:dedent: 8
:caption: Creating the ContainerClient from a connection string.
"""
account_url, secondary, credential = parse_connection_str(conn_str, credential, 'blob')
if 'secondary_hostname' not in kwargs:
kwargs['secondary_hostname'] = secondary
return cls(
account_url, container_name=container_name, credential=credential, **kwargs)
@distributed_trace
def create_container(self, metadata=None, public_access=None, **kwargs):
# type: (Optional[Dict[str, str]], Optional[Union[PublicAccess, str]], **Any) -> Dict[str, Union[str, datetime]]
"""
Creates a new container under the specified account. If the container
with the same name already exists, the operation fails.
:param metadata:
A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
:type metadata: dict[str, str]
:param ~azure.storage.blob.PublicAccess public_access:
Possible values include: 'container', 'blob'.
:keyword container_encryption_scope:
Specifies the default encryption scope to set on the container and use for
all future writes.
.. versionadded:: 12.2.0
:paramtype container_encryption_scope: dict or ~azure.storage.blob.ContainerEncryptionScope
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: A dictionary of response headers.
:rtype: Dict[str, Union[str, datetime]]
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_containers.py
:start-after: [START create_container]
:end-before: [END create_container]
:language: python
:dedent: 12
:caption: Creating a container to store blobs.
"""
headers = kwargs.pop('headers', {})
timeout = kwargs.pop('timeout', None)
headers.update(add_metadata_headers(metadata)) # type: ignore
container_cpk_scope_info = get_container_cpk_scope_info(kwargs)
try:
return self._client.container.create( # type: ignore
timeout=timeout,
access=public_access,
container_cpk_scope_info=container_cpk_scope_info,
cls=return_response_headers,
headers=headers,
**kwargs)
except HttpResponseError as error:
process_storage_error(error)
@distributed_trace
def _rename_container(self, new_name, **kwargs):
# type: (str, **Any) -> ContainerClient
"""Renames a container.
Operation is successful only if the source container exists.
:param str new_name:
The new container name the user wants to rename to.
:keyword lease:
Specify this to perform only if the lease ID given
matches the active lease ID of the source container.
:type lease: ~azure.storage.blob.BlobLeaseClient or str
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: The renamed container client.
:rtype: ~azure.storage.blob.ContainerClient
"""
lease = kwargs.pop('lease', None)
try:
kwargs['source_lease_id'] = lease.id
except AttributeError:
kwargs['source_lease_id'] = lease
try:
renamed_container = ContainerClient(
f"{self.scheme}://{self.primary_hostname}", container_name=new_name,
credential=self.credential, api_version=self.api_version, _configuration=self._config,
_pipeline=self._pipeline, _location_mode=self._location_mode, _hosts=self._hosts,
require_encryption=self.require_encryption, encryption_version=self.encryption_version,
key_encryption_key=self.key_encryption_key, key_resolver_function=self.key_resolver_function)
renamed_container._client.container.rename(self.container_name, **kwargs) # pylint: disable = protected-access
return renamed_container
except HttpResponseError as error:
process_storage_error(error)
@distributed_trace
def delete_container(
self, **kwargs):
# type: (Any) -> None
"""
Marks the specified container for deletion. The container and any blobs
contained within it are later deleted during garbage collection.
:keyword lease:
If specified, delete_container only succeeds if the
container's lease is active and matches this ID.
Required if the container has an active lease.
:paramtype lease: ~azure.storage.blob.BlobLeaseClient or str
:keyword ~datetime.datetime if_modified_since:
A DateTime value. Azure expects the date value passed in to be UTC.
If timezone is included, any non-UTC datetimes will be converted to UTC.
If a date is passed in without timezone info, it is assumed to be UTC.
Specify this header to perform the operation only
if the resource has been modified since the specified time.
:keyword ~datetime.datetime if_unmodified_since:
A DateTime value. Azure expects the date value passed in to be UTC.
If timezone is included, any non-UTC datetimes will be converted to UTC.
If a date is passed in without timezone info, it is assumed to be UTC.
Specify this header to perform the operation only if
the resource has not been modified since the specified date/time.
:keyword str etag:
An ETag value, or the wildcard character (*). Used to check if the resource has changed,
and act according to the condition specified by the `match_condition` parameter.
:keyword ~azure.core.MatchConditions match_condition:
The match condition to use upon the etag.
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:rtype: None
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_containers.py
:start-after: [START delete_container]
:end-before: [END delete_container]
:language: python
:dedent: 12
:caption: Delete a container.
"""
lease = kwargs.pop('lease', None)
access_conditions = get_access_conditions(lease)
mod_conditions = get_modify_conditions(kwargs)
timeout = kwargs.pop('timeout', None)
try:
self._client.container.delete(
timeout=timeout,
lease_access_conditions=access_conditions,
modified_access_conditions=mod_conditions,
**kwargs)
except HttpResponseError as error:
process_storage_error(error)
@distributed_trace
def acquire_lease(
self, lease_duration=-1, # type: int
lease_id=None, # type: Optional[str]
**kwargs):
# type: (...) -> BlobLeaseClient
"""
Requests a new lease. If the container does not have an active lease,
the Blob service creates a lease on the container and returns a new
lease ID.
:param int lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. Default is -1 (infinite lease).
:param str lease_id:
Proposed lease ID, in a GUID string format. The Blob service returns
400 (Invalid request) if the proposed lease ID is not in the correct format.
:keyword ~datetime.datetime if_modified_since:
A DateTime value. Azure expects the date value passed in to be UTC.
If timezone is included, any non-UTC datetimes will be converted to UTC.
If a date is passed in without timezone info, it is assumed to be UTC.
Specify this header to perform the operation only
if the resource has been modified since the specified time.
:keyword ~datetime.datetime if_unmodified_since:
A DateTime value. Azure expects the date value passed in to be UTC.
If timezone is included, any non-UTC datetimes will be converted to UTC.
If a date is passed in without timezone info, it is assumed to be UTC.
Specify this header to perform the operation only if
the resource has not been modified since the specified date/time.
:keyword str etag:
An ETag value, or the wildcard character (*). Used to check if the resource has changed,
and act according to the condition specified by the `match_condition` parameter.
:keyword ~azure.core.MatchConditions match_condition:
The match condition to use upon the etag.
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: A BlobLeaseClient object, that can be run in a context manager.
:rtype: ~azure.storage.blob.BlobLeaseClient
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_containers.py
:start-after: [START acquire_lease_on_container]
:end-before: [END acquire_lease_on_container]
:language: python
:dedent: 8
:caption: Acquiring a lease on the container.
"""
lease = BlobLeaseClient(self, lease_id=lease_id) # type: ignore
kwargs.setdefault('merge_span', True)
timeout = kwargs.pop('timeout', None)
lease.acquire(lease_duration=lease_duration, timeout=timeout, **kwargs)
return lease
@distributed_trace
def get_account_information(self, **kwargs):
# type: (**Any) -> Dict[str, str]
"""Gets information related to the storage account.
The information can also be retrieved if the user has a SAS to a container or blob.
The keys in the returned dictionary include 'sku_name' and 'account_kind'.
:returns: A dict of account information (SKU and account type).
:rtype: dict(str, str)
"""
try:
return self._client.container.get_account_info(cls=return_response_headers, **kwargs) # type: ignore
except HttpResponseError as error:
process_storage_error(error)
@distributed_trace
def get_container_properties(self, **kwargs):
# type: (Any) -> ContainerProperties
"""Returns all user-defined metadata and system properties for the specified
container. The data returned does not include the container's list of blobs.
:keyword lease:
If specified, get_container_properties only succeeds if the
container's lease is active and matches this ID.
:paramtype lease: ~azure.storage.blob.BlobLeaseClient or str
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:return: Properties for the specified container within a container object.
:rtype: ~azure.storage.blob.ContainerProperties
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_containers.py
:start-after: [START get_container_properties]
:end-before: [END get_container_properties]
:language: python
:dedent: 12
:caption: Getting properties on the container.
"""
lease = kwargs.pop('lease', None)
access_conditions = get_access_conditions(lease)
timeout = kwargs.pop('timeout', None)
try:
response = self._client.container.get_properties(
timeout=timeout,
lease_access_conditions=access_conditions,
cls=deserialize_container_properties,
**kwargs)
except HttpResponseError as error:
process_storage_error(error)
response.name = self.container_name
return response # type: ignore
@distributed_trace
def exists(self, **kwargs):
# type: (**Any) -> bool
"""
Returns True if a container exists and returns False otherwise.
:kwarg int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: boolean
:rtype: bool
"""
try:
self._client.container.get_properties(**kwargs)
return True
except HttpResponseError as error:
try:
process_storage_error(error)
except ResourceNotFoundError:
return False
@distributed_trace
def set_container_metadata( # type: ignore
self, metadata=None, # type: Optional[Dict[str, str]]
**kwargs
):
# type: (...) -> Dict[str, Union[str, datetime]]
"""Sets one or more user-defined name-value pairs for the specified
container. Each call to this operation replaces all existing metadata
attached to the container. To remove all metadata from the container,
call this operation with no metadata dict.
:param metadata:
A dict containing name-value pairs to associate with the container as
metadata. Example: {'category':'test'}
:type metadata: dict[str, str]
:keyword lease:
If specified, set_container_metadata only succeeds if the
container's lease is active and matches this ID.
:paramtype lease: ~azure.storage.blob.BlobLeaseClient or str
:keyword ~datetime.datetime if_modified_since:
A DateTime value. Azure expects the date value passed in to be UTC.
If timezone is included, any non-UTC datetimes will be converted to UTC.
If a date is passed in without timezone info, it is assumed to be UTC.
Specify this header to perform the operation only
if the resource has been modified since the specified time.
:keyword ~datetime.datetime if_unmodified_since:
A DateTime value. Azure expects the date value passed in to be UTC.
If timezone is included, any non-UTC datetimes will be converted to UTC.
If a date is passed in without timezone info, it is assumed to be UTC.
Specify this header to perform the operation only if
the resource has not been modified since the specified date/time.
:keyword str etag:
An ETag value, or the wildcard character (*). Used to check if the resource has changed,
and act according to the condition specified by the `match_condition` parameter.
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: Container-updated property dict (Etag and last modified).
:rtype: dict[str, str or datetime]
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_containers.py
:start-after: [START set_container_metadata]
:end-before: [END set_container_metadata]
:language: python
:dedent: 12
:caption: Setting metadata on the container.
"""
headers = kwargs.pop('headers', {})
headers.update(add_metadata_headers(metadata))
lease = kwargs.pop('lease', None)
access_conditions = get_access_conditions(lease)
mod_conditions = get_modify_conditions(kwargs)
timeout = kwargs.pop('timeout', None)
try:
return self._client.container.set_metadata( # type: ignore
timeout=timeout,
lease_access_conditions=access_conditions,
modified_access_conditions=mod_conditions,
cls=return_response_headers,
headers=headers,
**kwargs)
except HttpResponseError as error:
process_storage_error(error)
@distributed_trace
def _get_blob_service_client(self): # pylint: disable=client-method-missing-kwargs
# type: (...) -> BlobServiceClient
"""Get a client to interact with the container's parent service account.
Defaults to current container's credentials.
:returns: A BlobServiceClient.
:rtype: ~azure.storage.blob.BlobServiceClient
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_service.py
:start-after: [START get_blob_service_client_from_container_client]
:end-before: [END get_blob_service_client_from_container_client]
:language: python
:dedent: 8
:caption: Get blob service client from container object.
"""
from ._blob_service_client import BlobServiceClient
if not isinstance(self._pipeline._transport, TransportWrapper): # pylint: disable = protected-access
_pipeline = Pipeline(
transport=TransportWrapper(self._pipeline._transport), # pylint: disable = protected-access
policies=self._pipeline._impl_policies # pylint: disable = protected-access
)
else:
_pipeline = self._pipeline # pylint: disable = protected-access
return BlobServiceClient(
f"{self.scheme}://{self.primary_hostname}",
credential=self._raw_credential, api_version=self.api_version, _configuration=self._config,
_location_mode=self._location_mode, _hosts=self._hosts, require_encryption=self.require_encryption,
encryption_version=self.encryption_version, key_encryption_key=self.key_encryption_key,
key_resolver_function=self.key_resolver_function, _pipeline=_pipeline)
@distributed_trace
def get_container_access_policy(self, **kwargs):
# type: (Any) -> Dict[str, Any]
"""Gets the permissions for the specified container.
The permissions indicate whether container data may be accessed publicly.
:keyword lease:
If specified, get_container_access_policy only succeeds if the
container's lease is active and matches this ID.
:paramtype lease: ~azure.storage.blob.BlobLeaseClient or str
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: Access policy information in a dict.
:rtype: dict[str, Any]
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_containers.py
:start-after: [START get_container_access_policy]
:end-before: [END get_container_access_policy]
:language: python
:dedent: 12
:caption: Getting the access policy on the container.
"""
lease = kwargs.pop('lease', None)
access_conditions = get_access_conditions(lease)
timeout = kwargs.pop('timeout', None)
try:
response, identifiers = self._client.container.get_access_policy(
timeout=timeout,
lease_access_conditions=access_conditions,
cls=return_headers_and_deserialized,
**kwargs)
except HttpResponseError as error:
process_storage_error(error)
return {
'public_access': response.get('blob_public_access'),
'signed_identifiers': identifiers or []
}
@distributed_trace
def set_container_access_policy(
self, signed_identifiers, # type: Dict[str, AccessPolicy]
public_access=None, # type: Optional[Union[str, PublicAccess]]
**kwargs
): # type: (...) -> Dict[str, Union[str, datetime]]
"""Sets the permissions for the specified container or stored access
policies that may be used with Shared Access Signatures. The permissions
indicate whether blobs in a container may be accessed publicly.
:param signed_identifiers:
A dictionary of access policies to associate with the container. The
dictionary may contain up to 5 elements. An empty dictionary
will clear the access policies set on the service.
:type signed_identifiers: dict[str, ~azure.storage.blob.AccessPolicy]
:param ~azure.storage.blob.PublicAccess public_access:
Possible values include: 'container', 'blob'.
:keyword lease:
Required if the container has an active lease. Value can be a BlobLeaseClient object
or the lease ID as a string.
:paramtype lease: ~azure.storage.blob.BlobLeaseClient or str
:keyword ~datetime.datetime if_modified_since:
A datetime value. Azure expects the date value passed in to be UTC.
If timezone is included, any non-UTC datetimes will be converted to UTC.
If a date is passed in without timezone info, it is assumed to be UTC.
Specify this header to perform the operation only
if the resource has been modified since the specified date/time.
:keyword ~datetime.datetime if_unmodified_since:
A datetime value. Azure expects the date value passed in to be UTC.
If timezone is included, any non-UTC datetimes will be converted to UTC.
If a date is passed in without timezone info, it is assumed to be UTC.
Specify this header to perform the operation only if
the resource has not been modified since the specified date/time.
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: Container-updated property dict (Etag and last modified).
:rtype: dict[str, str or ~datetime.datetime]
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_containers.py
:start-after: [START set_container_access_policy]
:end-before: [END set_container_access_policy]
:language: python
:dedent: 12
:caption: Setting access policy on the container.
"""
if len(signed_identifiers) > 5:
raise ValueError(
'Too many access policies provided. The server does not support setting '
'more than 5 access policies on a single resource.')
identifiers = []
for key, value in signed_identifiers.items():
if value:
value.start = serialize_iso(value.start)
value.expiry = serialize_iso(value.expiry)
identifiers.append(SignedIdentifier(id=key, access_policy=value)) # type: ignore
signed_identifiers = identifiers # type: ignore
lease = kwargs.pop('lease', None)
mod_conditions = get_modify_conditions(kwargs)
access_conditions = get_access_conditions(lease)
timeout = kwargs.pop('timeout', None)
try:
return self._client.container.set_access_policy(
container_acl=signed_identifiers or None,
timeout=timeout,
access=public_access,
lease_access_conditions=access_conditions,
modified_access_conditions=mod_conditions,
cls=return_response_headers,
**kwargs)
except HttpResponseError as error:
process_storage_error(error)
@distributed_trace
def list_blobs(
self, name_starts_with: Optional[str] = None,
include: Optional[Union[str, List[str]]] = None,
**kwargs: Any
) -> ItemPaged[BlobProperties]:
"""Returns a generator to list the blobs under the specified container.
The generator will lazily follow the continuation tokens returned by
the service.
:param str name_starts_with:
Filters the results to return only blobs whose names
begin with the specified prefix.
:param include:
Specifies one or more additional datasets to include in the response.
Options include: 'snapshots', 'metadata', 'uncommittedblobs', 'copy', 'deleted', 'deletedwithversions',
'tags', 'versions', 'immutabilitypolicy', 'legalhold'.
:type include: list[str] or str
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: An iterable (auto-paging) response of BlobProperties.
:rtype: ~azure.core.paging.ItemPaged[~azure.storage.blob.BlobProperties]
.. admonition:: Example:
.. literalinclude:: ../samples/blob_samples_containers.py
:start-after: [START list_blobs_in_container]
:end-before: [END list_blobs_in_container]
:language: python
:dedent: 8
:caption: List the blobs in the container.
"""
if kwargs.pop('prefix', None):
raise ValueError("Passing 'prefix' has no effect on filtering, " +
"please use the 'name_starts_with' parameter instead.")
if include and not isinstance(include, list):
include = [include]
results_per_page = kwargs.pop('results_per_page', None)
timeout = kwargs.pop('timeout', None)
command = functools.partial(
self._client.container.list_blob_flat_segment,
include=include,
timeout=timeout,
**kwargs)
return ItemPaged(
command, prefix=name_starts_with, results_per_page=results_per_page,
page_iterator_class=BlobPropertiesPaged)
@distributed_trace
def list_blob_names(self, **kwargs: Any) -> ItemPaged[str]:
"""Returns a generator to list the names of blobs under the specified container.
The generator will lazily follow the continuation tokens returned by
the service.
Note that no additional properties or metadata will be returned when using this API.
Additionally, this API does not have an option to include additional blobs such as snapshots,
versions, soft-deleted blobs, etc. To get any of this data, use :func:`list_blobs()`.
:keyword str name_starts_with:
Filters the results to return only blobs whose names
begin with the specified prefix.
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: An iterable (auto-paging) response of blob names as strings.
:rtype: ~azure.core.paging.ItemPaged[str]
"""
if kwargs.pop('prefix', None):
raise ValueError("Passing 'prefix' has no effect on filtering, " +
"please use the 'name_starts_with' parameter instead.")
name_starts_with = kwargs.pop('name_starts_with', None)
results_per_page = kwargs.pop('results_per_page', None)
timeout = kwargs.pop('timeout', None)
# For listing only names we need to create a one-off generated client and
# override its deserializer to prevent deserialization of the full response.
client = self._build_generated_client()
client.container._deserialize = IgnoreListBlobsDeserializer() # pylint: disable=protected-access
command = functools.partial(
client.container.list_blob_flat_segment,
timeout=timeout,
**kwargs)
return ItemPaged(
command,
prefix=name_starts_with,
results_per_page=results_per_page,
page_iterator_class=BlobNamesPaged)
@distributed_trace
def walk_blobs(
self, name_starts_with: Optional[str] = None,
include: Optional[Union[List[str], str]] = None,
delimiter: str = "/",
**kwargs: Any
) -> ItemPaged[BlobProperties]:
"""Returns a generator to list the blobs under the specified container.
The generator will lazily follow the continuation tokens returned by
the service. This operation will list blobs in accordance with a hierarchy,
as delimited by the specified delimiter character.
:param str name_starts_with:
Filters the results to return only blobs whose names
begin with the specified prefix.
:param include:
Specifies one or more additional datasets to include in the response.
Options include: 'snapshots', 'metadata', 'uncommittedblobs', 'copy', 'deleted', 'deletedwithversions',
'tags', 'versions', 'immutabilitypolicy', 'legalhold'.
:type include: list[str] or str
:param str delimiter:
When the request includes this parameter, the operation returns a BlobPrefix
element in the response body that acts as a placeholder for all blobs whose
names begin with the same substring up to the appearance of the delimiter
character. The delimiter may be a single character or a string.
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: An iterable (auto-paging) response of BlobProperties.
:rtype: ~azure.core.paging.ItemPaged[~azure.storage.blob.BlobProperties]
"""
if kwargs.pop('prefix', None):
raise ValueError("Passing 'prefix' has no effect on filtering, " +
"please use the 'name_starts_with' parameter instead.")
if include and not isinstance(include, list):
include = [include]
results_per_page = kwargs.pop('results_per_page', None)
timeout = kwargs.pop('timeout', None)
command = functools.partial(
self._client.container.list_blob_hierarchy_segment,
delimiter=delimiter,
include=include,
timeout=timeout,
**kwargs)
return BlobPrefix(
command,
prefix=name_starts_with,
results_per_page=results_per_page,
delimiter=delimiter)
@distributed_trace
def find_blobs_by_tags(
self, filter_expression, # type: str
**kwargs # type: Optional[Any]
):
# type: (...) -> ItemPaged[FilteredBlob]
"""Returns a generator to list the blobs under the specified container whose tags
match the given search expression.
The generator will lazily follow the continuation tokens returned by
the service.
:param str filter_expression:
The expression to find blobs whose tags matches the specified condition.
eg. "\"yourtagname\"='firsttag' and \"yourtagname2\"='secondtag'"
:keyword int results_per_page:
The max result per page when paginating.
:keyword int timeout:
Sets the server-side timeout for the operation in seconds. For more details see
https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-blob-service-operations.
This value is not tracked or validated on the client. To configure client-side network timesouts
see `here <https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-blob
#other-client--per-operation-configuration>`_.
:returns: An iterable (auto-paging) response of FilteredBlob.
:rtype: ~azure.core.paging.ItemPaged[~azure.storage.blob.BlobProperties]
"""
results_per_page = kwargs.pop('results_per_page', None)
timeout = kwargs.pop('timeout', None)
command = functools.partial(
self._client.container.filter_blobs,
timeout=timeout,
where=filter_expression,
**kwargs)
return ItemPaged(
command, results_per_page=results_per_page,
page_iterator_class=FilteredBlobPaged)
@distributed_trace
def upload_blob(
self, name: str,
data: Union[bytes, str, Iterable[AnyStr], IO[AnyStr]],
blob_type: Union[str, BlobType] = BlobType.BlockBlob,
length: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
**kwargs