-
Notifications
You must be signed in to change notification settings - Fork 154
/
blob.py
5052 lines (4177 loc) · 197 KB
/
blob.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 2014 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=too-many-lines
"""Create / interact with Google Cloud Storage blobs.
"""
import base64
import copy
import hashlib
from io import BytesIO
from io import TextIOWrapper
import logging
import mimetypes
import os
import re
from email.parser import HeaderParser
from urllib.parse import parse_qsl
from urllib.parse import quote
from urllib.parse import urlencode
from urllib.parse import urlsplit
from urllib.parse import urlunsplit
import warnings
from google import resumable_media
from google.resumable_media.requests import ChunkedDownload
from google.resumable_media.requests import Download
from google.resumable_media.requests import RawDownload
from google.resumable_media.requests import RawChunkedDownload
from google.resumable_media.requests import MultipartUpload
from google.resumable_media.requests import ResumableUpload
from google.api_core.iam import Policy
from google.cloud import exceptions
from google.cloud._helpers import _bytes_to_unicode
from google.cloud._helpers import _datetime_to_rfc3339
from google.cloud._helpers import _rfc3339_nanos_to_datetime
from google.cloud._helpers import _to_bytes
from google.cloud.exceptions import NotFound
from google.cloud.storage._helpers import _add_etag_match_headers
from google.cloud.storage._helpers import _add_generation_match_parameters
from google.cloud.storage._helpers import _PropertyMixin
from google.cloud.storage._helpers import _scalar_property
from google.cloud.storage._helpers import _bucket_bound_hostname_url
from google.cloud.storage._helpers import _raise_if_more_than_one_set
from google.cloud.storage._helpers import _api_core_retry_to_resumable_media_retry
from google.cloud.storage._helpers import _get_default_headers
from google.cloud.storage._helpers import _get_default_storage_base_url
from google.cloud.storage._signing import generate_signed_url_v2
from google.cloud.storage._signing import generate_signed_url_v4
from google.cloud.storage._helpers import _NUM_RETRIES_MESSAGE
from google.cloud.storage._helpers import _API_VERSION
from google.cloud.storage._helpers import _virtual_hosted_style_base_url
from google.cloud.storage._opentelemetry_tracing import create_trace_span
from google.cloud.storage.acl import ACL
from google.cloud.storage.acl import ObjectACL
from google.cloud.storage.constants import _DEFAULT_TIMEOUT
from google.cloud.storage.constants import ARCHIVE_STORAGE_CLASS
from google.cloud.storage.constants import COLDLINE_STORAGE_CLASS
from google.cloud.storage.constants import MULTI_REGIONAL_LEGACY_STORAGE_CLASS
from google.cloud.storage.constants import NEARLINE_STORAGE_CLASS
from google.cloud.storage.constants import REGIONAL_LEGACY_STORAGE_CLASS
from google.cloud.storage.constants import STANDARD_STORAGE_CLASS
from google.cloud.storage.retry import ConditionalRetryPolicy
from google.cloud.storage.retry import DEFAULT_RETRY
from google.cloud.storage.retry import DEFAULT_RETRY_IF_ETAG_IN_JSON
from google.cloud.storage.retry import DEFAULT_RETRY_IF_GENERATION_SPECIFIED
from google.cloud.storage.retry import DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED
from google.cloud.storage.fileio import BlobReader
from google.cloud.storage.fileio import BlobWriter
_DEFAULT_CONTENT_TYPE = "application/octet-stream"
_DOWNLOAD_URL_TEMPLATE = "{hostname}/download/storage/{api_version}{path}?alt=media"
_BASE_UPLOAD_TEMPLATE = (
"{hostname}/upload/storage/{api_version}{bucket_path}/o?uploadType="
)
_MULTIPART_URL_TEMPLATE = _BASE_UPLOAD_TEMPLATE + "multipart"
_RESUMABLE_URL_TEMPLATE = _BASE_UPLOAD_TEMPLATE + "resumable"
# NOTE: "acl" is also writeable but we defer ACL management to
# the classes in the google.cloud.storage.acl module.
_CONTENT_TYPE_FIELD = "contentType"
_WRITABLE_FIELDS = (
"cacheControl",
"contentDisposition",
"contentEncoding",
"contentLanguage",
_CONTENT_TYPE_FIELD,
"crc32c",
"customTime",
"md5Hash",
"metadata",
"name",
"retention",
"storageClass",
)
_READ_LESS_THAN_SIZE = (
"Size {:d} was specified but the file-like object only had " "{:d} bytes remaining."
)
_CHUNKED_DOWNLOAD_CHECKSUM_MESSAGE = (
"A checksum of type `{}` was requested, but checksumming is not available "
"for downloads when chunk_size is set."
)
_COMPOSE_IF_GENERATION_LIST_DEPRECATED = (
"'if_generation_match: type list' is deprecated and supported for "
"backwards-compatability reasons only. Use 'if_source_generation_match' "
"instead' to match source objects' generations."
)
_COMPOSE_IF_GENERATION_LIST_AND_IF_SOURCE_GENERATION_ERROR = (
"Use 'if_generation_match' to match the generation of the destination "
"object by passing in a generation number, instead of a list. "
"Use 'if_source_generation_match' to match source objects generations."
)
_COMPOSE_IF_METAGENERATION_LIST_DEPRECATED = (
"'if_metageneration_match: type list' is deprecated and supported for "
"backwards-compatability reasons only. Note that the metageneration to "
"be matched is that of the destination blob. Please pass in a single "
"value (type long)."
)
_COMPOSE_IF_SOURCE_GENERATION_MISMATCH_ERROR = (
"'if_source_generation_match' length must be the same as 'sources' length"
)
_DOWNLOAD_AS_STRING_DEPRECATED = (
"Blob.download_as_string() is deprecated and will be removed in future. "
"Use Blob.download_as_bytes() instead."
)
_GS_URL_REGEX_PATTERN = re.compile(
r"(?P<scheme>gs)://(?P<bucket_name>[a-z0-9_.-]+)/(?P<object_name>.+)"
)
_DEFAULT_CHUNKSIZE = 104857600 # 1024 * 1024 B * 100 = 100 MB
_MAX_MULTIPART_SIZE = 8388608 # 8 MB
_logger = logging.getLogger(__name__)
class Blob(_PropertyMixin):
"""A wrapper around Cloud Storage's concept of an ``Object``.
:type name: str
:param name: The name of the blob. This corresponds to the unique path of
the object in the bucket. If bytes, will be converted to a
unicode object. Blob / object names can contain any sequence
of valid unicode characters, of length 1-1024 bytes when
UTF-8 encoded.
:type bucket: :class:`google.cloud.storage.bucket.Bucket`
:param bucket: The bucket to which this blob belongs.
:type chunk_size: int
:param chunk_size:
(Optional) The size of a chunk of data whenever iterating (in bytes).
This must be a multiple of 256 KB per the API specification. If not
specified, the chunk_size of the blob itself is used. If that is not
specified, a default value of 40 MB is used.
:type encryption_key: bytes
:param encryption_key:
(Optional) 32 byte encryption key for customer-supplied encryption.
See https://cloud.google.com/storage/docs/encryption#customer-supplied.
:type kms_key_name: str
:param kms_key_name:
(Optional) Resource name of Cloud KMS key used to encrypt the blob's
contents.
:type generation: long
:param generation:
(Optional) If present, selects a specific revision of this object.
"""
_chunk_size = None # Default value for each instance.
_CHUNK_SIZE_MULTIPLE = 256 * 1024
"""Number (256 KB, in bytes) that must divide the chunk size."""
STORAGE_CLASSES = (
STANDARD_STORAGE_CLASS,
NEARLINE_STORAGE_CLASS,
COLDLINE_STORAGE_CLASS,
ARCHIVE_STORAGE_CLASS,
MULTI_REGIONAL_LEGACY_STORAGE_CLASS,
REGIONAL_LEGACY_STORAGE_CLASS,
)
"""Allowed values for :attr:`storage_class`.
See
https://cloud.google.com/storage/docs/json_api/v1/objects#storageClass
https://cloud.google.com/storage/docs/per-object-storage-class
.. note::
This list does not include 'DURABLE_REDUCED_AVAILABILITY', which
is only documented for buckets (and deprecated).
"""
def __init__(
self,
name,
bucket,
chunk_size=None,
encryption_key=None,
kms_key_name=None,
generation=None,
):
"""
property :attr:`name`
Get the blob's name.
"""
name = _bytes_to_unicode(name)
super(Blob, self).__init__(name=name)
self.chunk_size = chunk_size # Check that setter accepts value.
self._bucket = bucket
self._acl = ObjectACL(self)
_raise_if_more_than_one_set(
encryption_key=encryption_key, kms_key_name=kms_key_name
)
self._encryption_key = encryption_key
if kms_key_name is not None:
self._properties["kmsKeyName"] = kms_key_name
if generation is not None:
self._properties["generation"] = generation
@property
def bucket(self):
"""Bucket which contains the object.
:rtype: :class:`~google.cloud.storage.bucket.Bucket`
:returns: The object's bucket.
"""
return self._bucket
@property
def chunk_size(self):
"""Get the blob's default chunk size.
:rtype: int or ``NoneType``
:returns: The current blob's chunk size, if it is set.
"""
return self._chunk_size
@chunk_size.setter
def chunk_size(self, value):
"""Set the blob's default chunk size.
:type value: int
:param value: (Optional) The current blob's chunk size, if it is set.
:raises: :class:`ValueError` if ``value`` is not ``None`` and is not a
multiple of 256 KB.
"""
if value is not None and value > 0 and value % self._CHUNK_SIZE_MULTIPLE != 0:
raise ValueError(
"Chunk size must be a multiple of %d." % (self._CHUNK_SIZE_MULTIPLE,)
)
self._chunk_size = value
@property
def encryption_key(self):
"""Retrieve the customer-supplied encryption key for the object.
:rtype: bytes or ``NoneType``
:returns:
The encryption key or ``None`` if no customer-supplied encryption key was used,
or the blob's resource has not been loaded from the server.
"""
return self._encryption_key
@encryption_key.setter
def encryption_key(self, value):
"""Set the blob's encryption key.
See https://cloud.google.com/storage/docs/encryption#customer-supplied
To perform a key rotation for an encrypted blob, use :meth:`rewrite`.
See https://cloud.google.com/storage/docs/encryption/using-customer-supplied-keys?hl=ca#rotating
:type value: bytes
:param value: 32 byte encryption key for customer-supplied encryption.
"""
self._encryption_key = value
@staticmethod
def path_helper(bucket_path, blob_name):
"""Relative URL path for a blob.
:type bucket_path: str
:param bucket_path: The URL path for a bucket.
:type blob_name: str
:param blob_name: The name of the blob.
:rtype: str
:returns: The relative URL path for ``blob_name``.
"""
return bucket_path + "/o/" + _quote(blob_name)
@property
def acl(self):
"""Create our ACL on demand."""
return self._acl
def __repr__(self):
if self.bucket:
bucket_name = self.bucket.name
else:
bucket_name = None
return f"<Blob: {bucket_name}, {self.name}, {self.generation}>"
@property
def path(self):
"""Getter property for the URL path to this Blob.
:rtype: str
:returns: The URL path to this Blob.
"""
if not self.name:
raise ValueError("Cannot determine path without a blob name.")
return self.path_helper(self.bucket.path, self.name)
@property
def client(self):
"""The client bound to this blob."""
return self.bucket.client
@property
def user_project(self):
"""Project ID billed for API requests made via this blob.
Derived from bucket's value.
:rtype: str
"""
return self.bucket.user_project
def _encryption_headers(self):
"""Return any encryption headers needed to fetch the object.
:rtype: List(Tuple(str, str))
:returns: a list of tuples to be passed as headers.
"""
return _get_encryption_headers(self._encryption_key)
@property
def _query_params(self):
"""Default query parameters."""
params = {}
if self.generation is not None:
params["generation"] = self.generation
if self.user_project is not None:
params["userProject"] = self.user_project
return params
@property
def public_url(self):
"""The public URL for this blob.
Use :meth:`make_public` to enable anonymous access via the returned
URL.
:rtype: `string`
:returns: The public URL for this blob.
"""
if self.client:
endpoint = self.client.api_endpoint
else:
endpoint = _get_default_storage_base_url()
return "{storage_base_url}/{bucket_name}/{quoted_name}".format(
storage_base_url=endpoint,
bucket_name=self.bucket.name,
quoted_name=_quote(self.name, safe=b"/~"),
)
@classmethod
def from_string(cls, uri, client=None):
"""Get a constructor for blob object by URI.
.. code-block:: python
from google.cloud import storage
from google.cloud.storage.blob import Blob
client = storage.Client()
blob = Blob.from_string("gs://bucket/object", client=client)
:type uri: str
:param uri: The blob uri following a gs://bucket/object pattern.
Both a bucket and object name is required to construct a blob object.
:type client: :class:`~google.cloud.storage.client.Client`
:param client:
(Optional) The client to use. Application code should
*always* pass ``client``.
:rtype: :class:`google.cloud.storage.blob.Blob`
:returns: The blob object created.
"""
from google.cloud.storage.bucket import Bucket
match = _GS_URL_REGEX_PATTERN.match(uri)
if not match:
raise ValueError("URI pattern must be gs://bucket/object")
bucket = Bucket(client, name=match.group("bucket_name"))
return cls(match.group("object_name"), bucket)
def generate_signed_url(
self,
expiration=None,
api_access_endpoint=None,
method="GET",
content_md5=None,
content_type=None,
response_disposition=None,
response_type=None,
generation=None,
headers=None,
query_parameters=None,
client=None,
credentials=None,
version=None,
service_account_email=None,
access_token=None,
virtual_hosted_style=False,
bucket_bound_hostname=None,
scheme="http",
):
"""Generates a signed URL for this blob.
.. note::
If you are on Google Compute Engine, you can't generate a signed
URL using GCE service account.
If you'd like to be able to generate a signed URL from GCE,
you can use a standard service account from a JSON file rather
than a GCE service account.
If you have a blob that you want to allow access to for a set
amount of time, you can use this method to generate a URL that
is only valid within a certain time period.
See a [code sample](https://cloud.google.com/storage/docs/samples/storage-generate-signed-url-v4#storage_generate_signed_url_v4-python).
This is particularly useful if you don't want publicly
accessible blobs, but don't want to require users to explicitly
log in.
If ``bucket_bound_hostname`` is set as an argument of :attr:`api_access_endpoint`,
``https`` works only if using a ``CDN``.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration:
Point in time when the signed URL should expire. If a ``datetime``
instance is passed without an explicit ``tzinfo`` set, it will be
assumed to be ``UTC``.
:type api_access_endpoint: str
:param api_access_endpoint: (Optional) URI base, for instance
"https://storage.googleapis.com". If not specified, the client's
api_endpoint will be used. Incompatible with bucket_bound_hostname.
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
:type content_md5: str
:param content_md5:
(Optional) The MD5 hash of the object referenced by ``resource``.
:type content_type: str
:param content_type:
(Optional) The content type of the object referenced by
``resource``.
:type response_disposition: str
:param response_disposition:
(Optional) Content disposition of responses to requests for the
signed URL. For example, to enable the signed URL to initiate a
file of ``blog.png``, use the value ``'attachment;
filename=blob.png'``.
:type response_type: str
:param response_type:
(Optional) Content type of responses to requests for the signed
URL. Ignored if content_type is set on object/blob metadata.
:type generation: str
:param generation:
(Optional) A value that indicates which generation of the resource
to fetch.
:type headers: dict
:param headers:
(Optional) Additional HTTP headers to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers
Requests using the signed URL *must* pass the specified header
(name and value) with each request for the URL.
:type query_parameters: dict
:param query_parameters:
(Optional) Additional query parameters to be included as part of the
signed URLs. See:
https://cloud.google.com/storage/docs/xml-api/reference-headers#query
:type client: :class:`~google.cloud.storage.client.Client`
:param client:
(Optional) The client to use. If not passed, falls back to the
``client`` stored on the blob's bucket.
:type credentials: :class:`google.auth.credentials.Credentials`
:param credentials:
(Optional) The authorization credentials to attach to requests.
These credentials identify this application to the service. If
none are specified, the client will attempt to ascertain the
credentials from the environment.
:type version: str
:param version:
(Optional) The version of signed credential to create. Must be one
of 'v2' | 'v4'.
:type service_account_email: str
:param service_account_email:
(Optional) E-mail address of the service account.
:type access_token: str
:param access_token: (Optional) Access token for a service account.
:type virtual_hosted_style: bool
:param virtual_hosted_style:
(Optional) If true, then construct the URL relative the bucket's
virtual hostname, e.g., '<bucket-name>.storage.googleapis.com'.
Incompatible with bucket_bound_hostname.
:type bucket_bound_hostname: str
:param bucket_bound_hostname:
(Optional) If passed, then construct the URL relative to the bucket-bound hostname.
Value can be a bare or with scheme, e.g., 'example.com' or 'http://example.com'.
Incompatible with api_access_endpoint and virtual_hosted_style.
See: https://cloud.google.com/storage/docs/request-endpoints#cname
:type scheme: str
:param scheme:
(Optional) If ``bucket_bound_hostname`` is passed as a bare
hostname, use this value as the scheme. ``https`` will work only
when using a CDN. Defaults to ``"http"``.
:raises: :exc:`ValueError` when version is invalid or mutually exclusive arguments are used.
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
:rtype: str
:returns: A signed URL you can use to access the resource
until expiration.
"""
if version is None:
version = "v2"
elif version not in ("v2", "v4"):
raise ValueError("'version' must be either 'v2' or 'v4'")
if (
api_access_endpoint is not None or virtual_hosted_style
) and bucket_bound_hostname:
raise ValueError(
"The bucket_bound_hostname argument is not compatible with "
"either api_access_endpoint or virtual_hosted_style."
)
if api_access_endpoint is None:
client = self._require_client(client)
api_access_endpoint = client.api_endpoint
quoted_name = _quote(self.name, safe=b"/~")
# If you are on Google Compute Engine, you can't generate a signed URL
# using GCE service account.
# See https://github.com/googleapis/google-auth-library-python/issues/50
if virtual_hosted_style:
api_access_endpoint = _virtual_hosted_style_base_url(
api_access_endpoint, self.bucket.name
)
resource = f"/{quoted_name}"
elif bucket_bound_hostname:
api_access_endpoint = _bucket_bound_hostname_url(
bucket_bound_hostname, scheme
)
resource = f"/{quoted_name}"
else:
resource = f"/{self.bucket.name}/{quoted_name}"
if credentials is None:
client = self._require_client(client) # May be redundant, but that's ok.
credentials = client._credentials
client = self._require_client(client)
universe_domain = client.universe_domain
if version == "v2":
helper = generate_signed_url_v2
else:
helper = generate_signed_url_v4
if self._encryption_key is not None:
encryption_headers = _get_encryption_headers(self._encryption_key)
if headers is None:
headers = {}
if version == "v2":
# See: https://cloud.google.com/storage/docs/access-control/signed-urls-v2#about-canonical-extension-headers
v2_copy_only = "X-Goog-Encryption-Algorithm"
headers[v2_copy_only] = encryption_headers[v2_copy_only]
else:
headers.update(encryption_headers)
return helper(
credentials,
resource=resource,
expiration=expiration,
api_access_endpoint=api_access_endpoint,
method=method.upper(),
content_md5=content_md5,
content_type=content_type,
response_type=response_type,
response_disposition=response_disposition,
generation=generation,
headers=headers,
query_parameters=query_parameters,
service_account_email=service_account_email,
access_token=access_token,
universe_domain=universe_domain,
)
@create_trace_span(name="Storage.Blob.exists")
def exists(
self,
client=None,
if_etag_match=None,
if_etag_not_match=None,
if_generation_match=None,
if_generation_not_match=None,
if_metageneration_match=None,
if_metageneration_not_match=None,
timeout=_DEFAULT_TIMEOUT,
retry=DEFAULT_RETRY,
soft_deleted=None,
):
"""Determines whether or not this blob exists.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client`
:param client:
(Optional) The client to use. If not passed, falls back to the
``client`` stored on the blob's bucket.
:type if_etag_match: Union[str, Set[str]]
:param if_etag_match:
(Optional) See :ref:`using-if-etag-match`
:type if_etag_not_match: Union[str, Set[str]]
:param if_etag_not_match:
(Optional) See :ref:`using-if-etag-not-match`
:type if_generation_match: long
:param if_generation_match:
(Optional) See :ref:`using-if-generation-match`
:type if_generation_not_match: long
:param if_generation_not_match:
(Optional) See :ref:`using-if-generation-not-match`
:type if_metageneration_match: long
:param if_metageneration_match:
(Optional) See :ref:`using-if-metageneration-match`
:type if_metageneration_not_match: long
:param if_metageneration_not_match:
(Optional) See :ref:`using-if-metageneration-not-match`
:type timeout: float or tuple
:param timeout:
(Optional) The amount of time, in seconds, to wait
for the server response. See: :ref:`configuring_timeouts`
:type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
:param retry:
(Optional) How to retry the RPC. See: :ref:`configuring_retries`
:type soft_deleted: bool
:param soft_deleted:
(Optional) If True, looks for a soft-deleted object. Will only return True
if the object exists and is in a soft-deleted state.
:attr:`generation` is required to be set on the blob if ``soft_deleted`` is set to True.
See: https://cloud.google.com/storage/docs/soft-delete
:rtype: bool
:returns: True if the blob exists in Cloud Storage.
"""
client = self._require_client(client)
# We only need the status code (200 or not) so we seek to
# minimize the returned payload.
query_params = self._query_params
query_params["fields"] = "name"
if soft_deleted is not None:
query_params["softDeleted"] = soft_deleted
_add_generation_match_parameters(
query_params,
if_generation_match=if_generation_match,
if_generation_not_match=if_generation_not_match,
if_metageneration_match=if_metageneration_match,
if_metageneration_not_match=if_metageneration_not_match,
)
headers = {}
_add_etag_match_headers(
headers, if_etag_match=if_etag_match, if_etag_not_match=if_etag_not_match
)
try:
# We intentionally pass `_target_object=None` since fields=name
# would limit the local properties.
client._get_resource(
self.path,
query_params=query_params,
headers=headers,
timeout=timeout,
retry=retry,
_target_object=None,
)
except NotFound:
# NOTE: This will not fail immediately in a batch. However, when
# Batch.finish() is called, the resulting `NotFound` will be
# raised.
return False
return True
@create_trace_span(name="Storage.Blob.delete")
def delete(
self,
client=None,
if_generation_match=None,
if_generation_not_match=None,
if_metageneration_match=None,
if_metageneration_not_match=None,
timeout=_DEFAULT_TIMEOUT,
retry=DEFAULT_RETRY_IF_GENERATION_SPECIFIED,
):
"""Deletes a blob from Cloud Storage.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client`
:param client:
(Optional) The client to use. If not passed, falls back to the
``client`` stored on the blob's bucket.
:type if_generation_match: long
:param if_generation_match:
(Optional) See :ref:`using-if-generation-match`
:type if_generation_not_match: long
:param if_generation_not_match:
(Optional) See :ref:`using-if-generation-not-match`
:type if_metageneration_match: long
:param if_metageneration_match:
(Optional) See :ref:`using-if-metageneration-match`
:type if_metageneration_not_match: long
:param if_metageneration_not_match:
(Optional) See :ref:`using-if-metageneration-not-match`
:type timeout: float or tuple
:param timeout:
(Optional) The amount of time, in seconds, to wait
for the server response. See: :ref:`configuring_timeouts`
:type retry: google.api_core.retry.Retry or google.cloud.storage.retry.ConditionalRetryPolicy
:param retry:
(Optional) How to retry the RPC.
The default value is ``DEFAULT_RETRY_IF_GENERATION_SPECIFIED``, a conditional retry
policy which will only enable retries if ``if_generation_match`` or ``generation``
is set, in order to ensure requests are idempotent before retrying them.
Change the value to ``DEFAULT_RETRY`` or another `google.api_core.retry.Retry` object
to enable retries regardless of generation precondition setting.
See [Configuring Retries](https://cloud.google.com/python/docs/reference/storage/latest/retry_timeout).
:raises: :class:`google.cloud.exceptions.NotFound`
(propagated from
:meth:`google.cloud.storage.bucket.Bucket.delete_blob`).
"""
self.bucket.delete_blob(
self.name,
client=client,
generation=self.generation,
timeout=timeout,
if_generation_match=if_generation_match,
if_generation_not_match=if_generation_not_match,
if_metageneration_match=if_metageneration_match,
if_metageneration_not_match=if_metageneration_not_match,
retry=retry,
)
def _get_transport(self, client):
"""Return the client's transport.
:type client: :class:`~google.cloud.storage.client.Client`
:param client:
(Optional) The client to use. If not passed, falls back to the
``client`` stored on the blob's bucket.
:rtype transport:
:class:`~google.auth.transport.requests.AuthorizedSession`
:returns: The transport (with credentials) that will
make authenticated requests.
"""
client = self._require_client(client)
return client._http
def _get_download_url(
self,
client,
if_generation_match=None,
if_generation_not_match=None,
if_metageneration_match=None,
if_metageneration_not_match=None,
):
"""Get the download URL for the current blob.
If the ``media_link`` has been loaded, it will be used, otherwise
the URL will be constructed from the current blob's path (and possibly
generation) to avoid a round trip.
:type client: :class:`~google.cloud.storage.client.Client`
:param client: The client to use.
:type if_generation_match: long
:param if_generation_match:
(Optional) See :ref:`using-if-generation-match`
:type if_generation_not_match: long
:param if_generation_not_match:
(Optional) See :ref:`using-if-generation-not-match`
:type if_metageneration_match: long
:param if_metageneration_match:
(Optional) See :ref:`using-if-metageneration-match`
:type if_metageneration_not_match: long
:param if_metageneration_not_match:
(Optional) See :ref:`using-if-metageneration-not-match`
:rtype: str
:returns: The download URL for the current blob.
"""
name_value_pairs = []
if self.media_link is None:
hostname = _get_host_name(client._connection)
base_url = _DOWNLOAD_URL_TEMPLATE.format(
hostname=hostname, path=self.path, api_version=_API_VERSION
)
if self.generation is not None:
name_value_pairs.append(("generation", f"{self.generation:d}"))
else:
base_url = self.media_link
if self.user_project is not None:
name_value_pairs.append(("userProject", self.user_project))
_add_generation_match_parameters(
name_value_pairs,
if_generation_match=if_generation_match,
if_generation_not_match=if_generation_not_match,
if_metageneration_match=if_metageneration_match,
if_metageneration_not_match=if_metageneration_not_match,
)
return _add_query_parameters(base_url, name_value_pairs)
def _extract_headers_from_download(self, response):
"""Extract headers from a non-chunked request's http object.
This avoids the need to make a second request for commonly used
headers.
:type response:
:class requests.models.Response
:param response: The server response from downloading a non-chunked file
"""
self._properties["contentEncoding"] = response.headers.get(
"Content-Encoding", None
)
self._properties[_CONTENT_TYPE_FIELD] = response.headers.get(
"Content-Type", None
)
self._properties["cacheControl"] = response.headers.get("Cache-Control", None)
self._properties["storageClass"] = response.headers.get(
"X-Goog-Storage-Class", None
)
self._properties["contentLanguage"] = response.headers.get(
"Content-Language", None
)
self._properties["etag"] = response.headers.get("ETag", None)
self._properties["generation"] = response.headers.get("X-goog-generation", None)
self._properties["metageneration"] = response.headers.get(
"X-goog-metageneration", None
)
# 'X-Goog-Hash': 'crc32c=4gcgLQ==,md5=CS9tHYTtyFntzj7B9nkkJQ==',
x_goog_hash = response.headers.get("X-Goog-Hash", "")
if x_goog_hash:
digests = {}
for encoded_digest in x_goog_hash.split(","):
match = re.match(r"(crc32c|md5)=([\w\d/\+/]+={0,3})", encoded_digest)
if match:
method, digest = match.groups()
digests[method] = digest
self._properties["crc32c"] = digests.get("crc32c", None)
self._properties["md5Hash"] = digests.get("md5", None)
def _do_download(
self,
transport,
file_obj,
download_url,
headers,
start=None,
end=None,
raw_download=False,
timeout=_DEFAULT_TIMEOUT,
checksum="md5",
retry=None,
):
"""Perform a download without any error handling.
This is intended to be called by :meth:`_prep_and_do_download` so it can
be wrapped with error handling / remapping.
:type transport:
:class:`~google.auth.transport.requests.AuthorizedSession`
:param transport:
The transport (with credentials) that will make authenticated
requests.
:type file_obj: file
:param file_obj: A file handle to which to write the blob's data.
:type download_url: str
:param download_url: The URL where the media can be accessed.
:type headers: dict
:param headers: Headers to be sent with the request(s).
:type start: int
:param start: (Optional) The first byte in a range to be downloaded.
:type end: int
:param end: (Optional) The last byte in a range to be downloaded.
:type raw_download: bool
:param raw_download:
(Optional) If true, download the object without any expansion.
:type timeout: float or tuple
:param timeout:
(Optional) The amount of time, in seconds, to wait
for the server response. See: :ref:`configuring_timeouts`
:type checksum: str
:param checksum:
(Optional) The type of checksum to compute to verify the integrity
of the object. The response headers must contain a checksum of the
requested type. If the headers lack an appropriate checksum (for
instance in the case of transcoded or ranged downloads where the
remote service does not know the correct checksum, including
downloads where chunk_size is set) an INFO-level log will be
emitted. Supported values are "md5", "crc32c" and None. The default
is "md5".
:type retry: google.api_core.retry.Retry
:param retry: (Optional) How to retry the RPC. A None value will disable
retries. A google.api_core.retry.Retry value will enable retries,
and the object will configure backoff and timeout options. Custom