- 3.5.0 (latest)
- 3.4.1
- 3.3.1
- 3.2.0
- 3.1.1
- 3.0.0
- 2.19.0
- 2.17.0
- 2.16.0
- 2.15.0
- 2.14.0
- 2.13.0
- 2.12.0
- 2.11.0
- 2.10.0
- 2.9.0
- 2.8.0
- 2.7.0
- 2.6.0
- 2.5.0
- 2.4.0
- 2.3.0
- 2.2.1
- 2.1.0
- 2.0.0
- 1.44.0
- 1.43.0
- 1.42.3
- 1.41.1
- 1.40.0
- 1.39.0
- 1.38.0
- 1.37.1
- 1.36.2
- 1.35.1
- 1.34.0
- 1.33.0
- 1.32.0
- 1.31.2
- 1.30.0
- 1.29.0
- 1.28.1
- 1.27.0
- 1.26.0
- 1.25.0
- 1.24.1
- 1.23.0
- 1.22.0
- 1.21.0
- 1.20.0
- 1.19.0
- 1.18.0
- 1.17.0
Blobs / Objects
Create / interact with Google Cloud Storage blobs.
class google.cloud.storage.blob.Blob(name, bucket, chunk_size=None, encryption_key=None, kms_key_name=None, generation=None)
Bases:google.cloud.storage._helpers._PropertyMixin
A wrapper around Cloud Storage’s concept of anObject.
Parameters
name (str) – The name of the blob. This corresponds to the unique path ofthe object in the bucket. If bytes, will be converted to aunicode object. Blob / object names can contain any sequenceof valid unicode characters, of length 1-1024 bytes whenUTF-8 encoded.
bucket (
google.cloud.storage.bucket.Bucket) – The bucket to which this blob belongs.chunk_size (int) – (Optional) The size of a chunk of data whenever iterating (in bytes).This must be a multiple of 256 KB per the API specification.
encryption_key (bytes) – (Optional) 32 byte encryption key for customer-supplied encryption.Seehttps://cloud.google.com/storage/docs/encryption#customer-supplied.
kms_key_name (str) – (Optional) Resource name of Cloud KMS key used to encrypt the blob’scontents.
generation (long) – (Optional) If present, selects a specific revision ofthis object.
propertyname
Get the blob’s name.STORAGE_CLASSES( = ('STANDARD', 'NEARLINE', 'COLDLINE', 'ARCHIVE', 'MULTI_REGIONAL', 'REGIONAL' )
Allowed values forstorage_class.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects#storageClasshttps://cloud.google.com/storage/docs/per-object-storage-class
NOTE: This list does not include ‘DURABLE_REDUCED_AVAILABILITY’, whichis only documented for buckets (and deprecated).
property acl()
Create our ACL on demand.
property bucket()
Bucket which contains the object.
Return type
Returns
The object’s bucket.
property cache_control()
HTTP ‘Cache-Control’ header for this object.
SeeRFC 7234 andAPI reference docs.
Return type
str or
NoneType
property chunk_size()
Get the blob’s default chunk size.
Return type
int or
NoneTypeReturns
The current blob’s chunk size, if it is set.
property client()
The client bound to this blob.
property component_count()
Number of underlying components that make up this object.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
int or
NoneTypeReturns
The component count (in case of a composed object) or
Noneif the blob’s resource has not been loaded from the server. This property will not be set on objects not created viacompose.
compose(sources, client=None, timeout=60)
Concatenate source blobs into this one.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
sources (list of
Blob) – blobs whose contents will be composed into this blob.client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.timeout (float* or[tuple*](https://python.readthedocs.io/en/latest/library/stdtypes.html#tuple)) – (Optional) The amount of time, in seconds, to waitfor the server response.
Can also be passed as a tuple (connect_timeout, read_timeout).See
requests.Session.request()documentation for details.
property content_disposition()
HTTP ‘Content-Disposition’ header for this object.
SeeRFC 6266 andAPI reference docs.
Return type
str or
NoneType
property content_encoding()
HTTP ‘Content-Encoding’ header for this object.
SeeRFC 7231 andAPI reference docs.
Return type
str or
NoneType
property content_language()
HTTP ‘Content-Language’ header for this object.
SeeBCP47 andAPI reference docs.
Return type
str or
NoneType
property content_type()
HTTP ‘Content-Type’ header for this object.
SeeRFC 2616 andAPI reference docs.
Return type
str or
NoneType
property crc32c()
CRC32C checksum for this object.
This returns the blob’s CRC32C checksum. To retrieve the value, first use areload method of the Blob class which loads the blob’s properties from the server.
SeeRFC 4960 andAPI reference docs.
If not set before upload, the server will compute the hash.
Return type
str or
NoneType
Example
Retrieve the crc32c hash of blob.
>>> from google.cloud importstorage>>> client =storage.Client()>>> bucket = client.get_bucket("my-bucket-name")>>> blob = bucket.blob('my-blob')>>> blob.crc32c # return None>>> blob.reload()>>> blob.crc32c # return crc32c hash>>> # Another approach>>> blob = bucket.get_blob('my-blob')>>> blob.crc32c # return crc32c hashcreate_resumable_upload_session(content_type=None, size=None, origin=None, client=None)
Create a resumable upload session.
Resumable upload sessions allow you to start an upload session fromone client and complete the session in another. This method is calledby the initiator to set the metadata and limits. The initiator thenpasses the session URL to the client that will upload the binary data.The client performs a PUT request on the session URL to complete theupload. This process allows untrusted clients to upload to anaccess-controlled bucket. For more details, see thedocumentation on signed URLs.
The content type of the upload will be determined in orderof precedence:
The value passed in to this method (if not
None)The value stored on the current blob
The default value (‘application/octet-stream’)
NOTE: The effect of uploading to an existing blob depends on the“versioning” and “lifecycle” policies defined on the blob’sbucket. In the absence of those policies, upload willoverwrite any existing contents.
See theobject versioning andlifecycleAPI documents for details.
Ifencryption_key is set, the blob will be encrypted withacustomer-supplied encryption key.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
size (int) – (Optional) The maximum number of bytes that can beuploaded using this session. If the size is not knownwhen creating the session, this should be left blank.
content_type (str) – (Optional) Type of content being uploaded.
origin (str) – (Optional) If set, the upload can only be completedby a user-agent that uploads from the given origin. Thiscan be useful when passing the session to a web client.
client (
Client) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.
Return type
Returns
The resumable upload session URL. The upload can be completed by making an HTTP PUT request with the file’s contents.
Raises
google.cloud.exceptions.GoogleCloudErrorif the session creation response returns an error status.
delete(client=None, timeout=60)
Deletes a blob from Cloud Storage.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.timeout (float* or[tuple*](https://python.readthedocs.io/en/latest/library/stdtypes.html#tuple)) – (Optional) The amount of time, in seconds, to waitfor the server response.
Can also be passed as a tuple (connect_timeout, read_timeout).See
requests.Session.request()documentation for details.
Raises
google.cloud.exceptions.NotFound(propagated fromgoogle.cloud.storage.bucket.Bucket.delete_blob()).
download_as_string(client=None, start=None, end=None, raw_download=False)
Download the contents of this blob as a bytes object.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.start (int) – (Optional) The first byte in a range to be downloaded.
end (int) – (Optional) The last byte in a range to be downloaded.
raw_download (bool) – (Optional) If true, download the object without any expansion.
Return type
Returns
The data stored in this blob.
Raises
google.cloud.exceptions.NotFound
download_to_file(file_obj, client=None, start=None, end=None, raw_download=False)
Download the contents of this blob into a file-like object.
NOTE: If the server-set property,media_link, is not yetinitialized, makes an additional API request to load it.
Downloading a file that has been encrypted with acustomer-suppliedencryption key:
from google.cloud.storage importBlobclient =storage.Client(project="my-project")bucket = client.get_bucket("my-bucket")encryption_key = "c7f32af42e45e85b9848a6a14dd2a8f6"blob = Blob("secure-data", bucket, encryption_key=encryption_key)blob.upload_from_string("my secret message.")with open("/tmp/my-secure-file", "wb") as file_obj: blob.download_to_file(file_obj)
Theencryption_key should be a str or bytes with a length of atleast 32.
For more fine-grained control over the download process, check outgoogle-resumable-media. For example, this library allowsdownloadingparts of a blob rather than the whole thing.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
file_obj (file) – A file handle to which to write the blob’s data.
client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.start (int) – (Optional) The first byte in a range to be downloaded.
end (int) – (Optional) The last byte in a range to be downloaded.
raw_download (bool) – (Optional) If true, download the object without any expansion.
Raises
google.cloud.exceptions.NotFound
download_to_filename(filename, client=None, start=None, end=None, raw_download=False)
Download the contents of this blob into a named file.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
filename (str) – A filename to be passed to
open.client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.start (int) – (Optional) The first byte in a range to be downloaded.
end (int) – (Optional) The last byte in a range to be downloaded.
raw_download (bool) – (Optional) If true, download the object without any expansion.
Raises
google.cloud.exceptions.NotFound
property etag()
Retrieve the ETag for the object.
SeeRFC 2616 (etags) andAPI reference docs.
Return type
str or
NoneTypeReturns
The blob etag or
Noneif the blob’s resource has not been loaded from the server.
property event_based_hold()
Is an event-based hold active on the object?
If the property is not set locally, returnsNone.
Return type
bool or
NoneType
exists(client=None, timeout=60)
Determines whether or not this blob exists.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.timeout (float* or[tuple*](https://python.readthedocs.io/en/latest/library/stdtypes.html#tuple)) – (Optional) The amount of time, in seconds, to waitfor the server response.
Can also be passed as a tuple (connect_timeout, read_timeout).See
requests.Session.request()documentation for details.
Return type
Returns
True if the blob exists in Cloud Storage.
classmethod from_string(uri, client=None)
Get a constructor for blob object by URI.
Parameters
Return type
google.cloud.storage.blob.BlobReturns
The blob object created.
Example
Get a constructor for blob object by URI..
>>> from google.cloud importstorage>>> from google.cloud.storage.blob importBlob>>> client =storage.Client()>>> blob =Blob.from_string("gs://bucket/object")generate_signed_url(expiration=None, api_access_endpoint='https://storage.googleapis.com', 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 signedURL using GCE service account. FollowIssue 50 for updates onthis. 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 ratherthan a GCE service account.
If you have a blob that you want to allow access to for a setamount of time, you can use this method to generate a URL thatis only valid within a certain time period.
Ifbucket_bound_hostname is set as an argument ofapi_access_endpoint,https works only if using aCDN.
Example
Generates a signed URL for this blob using bucket_bound_hostname and scheme.
>>> from google.cloud importstorage>>> client =storage.Client()>>> bucket = client.get_bucket('my-bucket-name')>>> blob = client.get_blob('my-blob-name')>>> url = blob.generate_signed_url(expiration='url-expiration-time', bucket_bound_hostname='mydomain.tld',>>> version='v4')>>> url = blob.generate_signed_url(expiration='url-expiration-time', bucket_bound_hostname='mydomain.tld',>>> version='v4',scheme='https') # If using ``CDN``This is particularly useful if you don’t want publiclyaccessible blobs, but don’t want to require users to explicitlylog in.
Parameters
expiration (Union[Integer, *[datetime.datetime](https://python.readthedocs.io/en/latest/library/datetime.html#datetime.datetime),[datetime.timedelta](https://python.readthedocs.io/en/latest/library/datetime.html#datetime.timedelta)]*) – Point in time when the signed URL should expire.
api_access_endpoint (str) – (Optional) URI base.
method (str) – The HTTP verb that will be used when requesting the URL.
content_md5 (str) – (Optional) The MD5 hash of the object referenced by
resource.content_type (str) – (Optional) The content type of the objectreferenced by
resource.response_disposition (str) – (Optional) Content disposition ofresponses to requests for the signed URL.For example, to enable the signed URLto initiate a file of
blog.png, usethe value'attachment; filename=blob.png'.response_type (str) – (Optional) Content type of responses to requestsfor the signed URL. Ignored if content_type isset on object/blob metadata.
generation (str) – (Optional) A value that indicates which generationof the resource to fetch.
headers (dict) – (Optional) Additional HTTP headers to be included as part of thesigned URLs. See:https://cloud.google.com/storage/docs/xml-api/reference-headersRequests using the signed URLmust pass the specified header(name and value) with each request for the URL.
query_parameters (dict) – (Optional) Additional query parameters to be included as part of thesigned URLs. See:https://cloud.google.com/storage/docs/xml-api/reference-headers#query
client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.credentials (
google.auth.credentials.CredentialsorNoneType) – The authorization credentials to attach to requests.These credentials identify this application to the service.If none are specified, the client will attempt to ascertainthe credentials from the environment.version (str) – (Optional) The version of signed credential to create.Must be one of ‘v2’ | ‘v4’.
service_account_email (str) – (Optional) E-mail address of the service account.
access_token (str) – (Optional) Access token for a service account.
virtual_hosted_style (bool) – (Optional) If true, then construct the URL relative the bucket’svirtual hostname, e.g., ‘
bucket_bound_hostname (str) – (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’.See:https://cloud.google.com/storage/docs/request-endpoints#cname
scheme (str) – (Optional) If
bucket_bound_hostnameis passed as a bare hostname, usethis value as the scheme.httpswill work only when using a CDN.Defaults to"http".
Raises
ValueErrorwhen version is invalid.Raises
TypeErrorwhen expiration is not a valid type.Raises
AttributeErrorif credentials is not an instance ofgoogle.auth.credentials.Signing.Return type
Returns
A signed URL you can use to access the resource until expiration.
property generation()
Retrieve the generation for the object.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
int or
NoneTypeReturns
The generation of the blob or
Noneif the blob’s resource has not been loaded from the server.
get_iam_policy(client=None, requested_policy_version=None, timeout=60)
Retrieve the IAM policy for the object.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the current object’s bucket.requested_policy_version (int or
NoneType) – (Optional) The version of IAM policies to request.If a policy with a condition is requested withoutsetting this, the server will return an error.This must be set to a value of 3 to retrieve IAMpolicies containing conditions. This is to preventclient code that isn’t aware of IAM conditions frominterpreting and modifying policies incorrectly.The service might return a policy with version lowerthan the one that was requested, based on thefeature syntax in the policy fetched.timeout (float* or[tuple*](https://python.readthedocs.io/en/latest/library/stdtypes.html#tuple)) – (Optional) The amount of time, in seconds, to waitfor the server response.
Can also be passed as a tuple (connect_timeout, read_timeout).See
requests.Session.request()documentation for details.
Return type
Returns
the policy instance, based on the resource returned from the
getIamPolicyAPI request.
property id()
Retrieve the ID for the object.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
The ID consists of the bucket name, object name, and generation number.
Return type
str or
NoneTypeReturns
The ID of the blob or
Noneif the blob’s resource has not been loaded from the server.
property kms_key_name()
Resource name of Cloud KMS key used to encrypt the blob’s contents.
Return type
str or
NoneTypeReturns
The resource name or
Noneif no Cloud KMS key was used, or the blob’s resource has not been loaded from the server.
make_private(client=None)
Update blob’s ACL, revoking read access for anonymous users.
Parameters
client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls back to theclientstored on the blob’s bucket.
make_public(client=None)
Update blob’s ACL, granting read access to anonymous users.
Parameters
client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls back to theclientstored on the blob’s bucket.
property md5_hash()
MD5 hash for this object.
This returns the blob’s MD5 hash. To retrieve the value, first use areload method of the Blob class which loads the blob’s properties from the server.
SeeRFC 1321 andAPI reference docs.
If not set before upload, the server will compute the hash.
Return type
str or
NoneType
Example
Retrieve the md5 hash of blob.
>>> from google.cloud importstorage>>> client =storage.Client()>>> bucket = client.get_bucket("my-bucket-name")>>> blob = bucket.blob('my-blob')>>> blob.md5_hash # return None>>> blob.reload()>>> blob.md5_hash # return md5 hash>>> # Another approach>>> blob = bucket.get_blob('my-blob')>>> blob.md5_hash # return md5 hashproperty media_link()
Retrieve the media download URI for the object.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
str or
NoneTypeReturns
The media link for the blob or
Noneif the blob’s resource has not been loaded from the server.
property metadata()
Retrieve arbitrary/application specific metadata for the object.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Setter
Update arbitrary/application specific metadata for the object.
Getter
Retrieve arbitrary/application specific metadata for the object.
Return type
dict or
NoneTypeReturns
The metadata associated with the blob or
Noneif the property is not set.
property metageneration()
Retrieve the metageneration for the object.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
int or
NoneTypeReturns
The metageneration of the blob or
Noneif the blob’s resource has not been loaded from the server.
property owner()
Retrieve info about the owner of the object.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
dict or
NoneTypeReturns
Mapping of owner’s role/ID, or
Noneif the blob’s resource has not been loaded from the server.
patch(client=None, timeout=60)
Sends all changed properties in a PATCH request.
Updates the_properties with the response from the backend.
Ifuser_project is set, bills the API request to that project.
Parameters
client (
ClientorNoneType) – the client to use. If not passed, falls back to theclientstored on the current object.timeout (float* or[tuple*](https://python.readthedocs.io/en/latest/library/stdtypes.html#tuple)) – (Optional) The amount of time, in seconds, to waitfor the server response.
Can also be passed as a tuple (connect_timeout, read_timeout).See
requests.Session.request()documentation for details.
property path()
Getter property for the URL path to this Blob.
Return type
Returns
The URL path to this Blob.
static path_helper(bucket_path, blob_name)
Relative URL path for a blob.
Parameters
Return type
Returns
The relative URL path for
blob_name.
property public_url()
The public URL for this blob.
Usemake_public() to enable anonymous access via the returnedURL.
Return type
string
Returns
The public URL for this blob.
reload(client=None, timeout=60)
Reload properties from Cloud Storage.
Ifuser_project is set, bills the API request to that project.
Parameters
client (
ClientorNoneType) – the client to use. If not passed, falls back to theclientstored on the current object.timeout (float* or[tuple*](https://python.readthedocs.io/en/latest/library/stdtypes.html#tuple)) – (Optional) The amount of time, in seconds, to waitfor the server response.
Can also be passed as a tuple (connect_timeout, read_timeout).See
requests.Session.request()documentation for details.
property retention_expiration_time()
Retrieve timestamp at which the object’s retention period expires.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
datetime.datetimeorNoneTypeReturns
Datetime object parsed from RFC3339 valid timestamp, or
Noneif the property is not set locally.
rewrite(source, token=None, client=None, timeout=60)
Rewrite source blob into this one.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
source (
Blob) – blob whose contents will be rewritten into this blob.token (str) – (Optional) Token returned from an earlier, not-completedcall to rewrite the same source blob. If passed,result will include updated status, total bytes written.
client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.timeout (float* or[tuple*](https://python.readthedocs.io/en/latest/library/stdtypes.html#tuple)) – (Optional) The amount of time, in seconds, to waitfor the server response.
Can also be passed as a tuple (connect_timeout, read_timeout).See
requests.Session.request()documentation for details.
Return type
Returns
(token, bytes_rewritten, total_bytes), wheretokenis a rewrite token (Noneif the rewrite is complete),bytes_rewrittenis the number of bytes rewritten so far, andtotal_bytesis the total number of bytes to be rewritten.
property self_link()
Retrieve the URI for the object.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
str or
NoneTypeReturns
The self link for the blob or
Noneif the blob’s resource has not been loaded from the server.
set_iam_policy(policy, client=None, timeout=60)
Update the IAM policy for the bucket.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
policy (
google.api_core.iam.Policy) – policy instance used to update bucket’s IAM policy.client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the current bucket.timeout (float* or[tuple*](https://python.readthedocs.io/en/latest/library/stdtypes.html#tuple)) – (Optional) The amount of time, in seconds, to waitfor the server response.
Can also be passed as a tuple (connect_timeout, read_timeout).See
requests.Session.request()documentation for details.
Return type
Returns
the policy instance, based on the resource returned from the
setIamPolicyAPI request.
property size()
Size of the object, in bytes.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
int or
NoneTypeReturns
The size of the blob or
Noneif the blob’s resource has not been loaded from the server.
property storage_class()
Retrieve the storage class for the object.
This can only be set at blob / objectcreation time. If you’dlike to change the storage classafter the blob / object alreadyexists in a bucket, callupdate_storage_class() (which usesrewrite()).
Seehttps://cloud.google.com/storage/docs/storage-classes
Return type
str or
NoneTypeReturns
If set, one of
STANDARD_STORAGE_CLASS,NEARLINE_STORAGE_CLASS,COLDLINE_STORAGE_CLASS,ARCHIVE_STORAGE_CLASS,MULTI_REGIONAL_LEGACY_STORAGE_CLASS,REGIONAL_LEGACY_STORAGE_CLASS,DURABLE_REDUCED_AVAILABILITY_STORAGE_CLASS, elseNone.
property temporary_hold()
Is a temporary hold active on the object?
If the property is not set locally, returnsNone.
Return type
bool or
NoneType
test_iam_permissions(permissions, client=None, timeout=60)
API call: test permissions
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
permissions (list of string) – the permissions to check
client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the current bucket.timeout (float* or[tuple*](https://python.readthedocs.io/en/latest/library/stdtypes.html#tuple)) – (Optional) The amount of time, in seconds, to waitfor the server response.
Can also be passed as a tuple (connect_timeout, read_timeout).See
requests.Session.request()documentation for details.
Return type
list of string
Returns
the permissions returned by the
testIamPermissionsAPI request.
property time_created()
Retrieve the timestamp at which the object was created.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
datetime.datetimeorNoneTypeReturns
Datetime object parsed from RFC3339 valid timestamp, or
Noneif the blob’s resource has not been loaded from the server (seereload()).
property time_deleted()
Retrieve the timestamp at which the object was deleted.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
datetime.datetimeorNoneTypeReturns
Datetime object parsed from RFC3339 valid timestamp, or
Noneif the blob’s resource has not been loaded from the server (seereload()). If the blob has not been deleted, this will never be set.
update(client=None, timeout=60)
Sends all properties in a PUT request.
Updates the_properties with the response from the backend.
Ifuser_project is set, bills the API request to that project.
Parameters
client (
ClientorNoneType) – the client to use. If not passed, falls back to theclientstored on the current object.timeout (float* or[tuple*](https://python.readthedocs.io/en/latest/library/stdtypes.html#tuple)) – (Optional) The amount of time, in seconds, to waitfor the server response.
Can also be passed as a tuple (connect_timeout, read_timeout).See
requests.Session.request()documentation for details.
update_storage_class(new_class, client=None)
Update blob’s storage class via a rewrite-in-place. This helper willwait for the rewrite to complete before returning, so it may take sometime for large files.
Seehttps://cloud.google.com/storage/docs/per-object-storage-class
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
new_class (str) – new storage class for the object. One of:
NEARLINE_STORAGE_CLASS,COLDLINE_STORAGE_CLASS,ARCHIVE_STORAGE_CLASS,STANDARD_STORAGE_CLASS,MULTI_REGIONAL_LEGACY_STORAGE_CLASS,orREGIONAL_LEGACY_STORAGE_CLASS.client (
Client) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.
property updated()
Retrieve the timestamp at which the object was updated.
Seehttps://cloud.google.com/storage/docs/json_api/v1/objects
Return type
datetime.datetimeorNoneTypeReturns
Datetime object parsed from RFC3339 valid timestamp, or
Noneif the blob’s resource has not been loaded from the server (seereload()).
upload_from_file(file_obj, rewind=False, size=None, content_type=None, num_retries=None, client=None, predefined_acl=None, if_generation_match=None, if_generation_not_match=None, if_metageneration_match=None, if_metageneration_not_match=None)
Upload the contents of this blob from a file-like object.
The content type of the upload will be determined in orderof precedence:
The value passed in to this method (if not
None)The value stored on the current blob
The default value (‘application/octet-stream’)
NOTE: The effect of uploading to an existing blob depends on the“versioning” and “lifecycle” policies defined on the blob’sbucket. In the absence of those policies, upload willoverwrite any existing contents.
See theobject versioning andlifecycle API documentsfor details.
Uploading a file with acustomer-supplied encryption key:
from google.cloud.storage importBlobclient =storage.Client(project="my-project")bucket = client.get_bucket("my-bucket")encryption_key = "aa426195405adee2c8081bb9e7e74b19"blob = Blob("secure-data", bucket, encryption_key=encryption_key)with open("my-file", "rb") as my_file: blob.upload_from_file(my_file)Theencryption_key should be a str or bytes with a length of atleast 32.
For more fine-grained over the upload process, check outgoogle-resumable-media.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
file_obj (file) – A file handle open for reading.
rewind (bool) – If True, seek to the beginning of the file handle beforewriting the file to Cloud Storage.
size (int) – The number of bytes to be uploaded (which will be readfrom
file_obj). If not provided, the upload will beconcluded oncefile_objis exhausted.content_type (str) – (Optional) Type of content being uploaded.
num_retries (int) – Number of upload retries. (Deprecated: Thisargument will be removed in a future release.)
client (
Client) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.predefined_acl (str) – (Optional) Predefined access control list
if_generation_match (long) – (Optional) Make the operation conditional on whetherthe blob’s current generation matches the given value.Setting to 0 makes the operation succeed only if thereare no live versions of the blob.
if_generation_not_match (long) – (Optional) Make the operation conditional on whetherthe blob’s current generation does not match the givenvalue. If no live blob exists, the precondition fails.Setting to 0 makes the operation succeed only if thereis a live version of the blob.
if_metageneration_match (long) – (Optional) Make the operation conditional on whether theblob’s current metageneration matches the given value.
if_metageneration_not_match (long) – (Optional) Make the operation conditional on whether theblob’s current metageneration does not match the given value.
Raises
GoogleCloudErrorif the upload response returns an error status.
upload_from_filename(filename, content_type=None, client=None, predefined_acl=None, if_generation_match=None, if_generation_not_match=None, if_metageneration_match=None, if_metageneration_not_match=None)
Upload this blob’s contents from the content of a named file.
The content type of the upload will be determined in orderof precedence:
The value passed in to this method (if not
None)The value stored on the current blob
The value given by
mimetypes.guess_typeThe default value (‘application/octet-stream’)
NOTE: The effect of uploading to an existing blob depends on the“versioning” and “lifecycle” policies defined on the blob’sbucket. In the absence of those policies, upload willoverwrite any existing contents.
See theobject versioning andlifecycleAPI documents for details.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
filename (str) – The path to the file.
content_type (str) – (Optional) Type of content being uploaded.
client (
Client) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.predefined_acl (str) – (Optional) Predefined access control list
if_generation_match (long) – (Optional) Make the operation conditional on whetherthe blob’s current generation matches the given value.Setting to 0 makes the operation succeed only if thereare no live versions of the blob.
if_generation_not_match (long) – (Optional) Make the operation conditional on whetherthe blob’s current generation does not match the givenvalue. If no live blob exists, the precondition fails.Setting to 0 makes the operation succeed only if thereis a live version of the blob.
if_metageneration_match (long) – (Optional) Make the operation conditional on whether theblob’s current metageneration matches the given value.
if_metageneration_not_match (long) – (Optional) Make the operation conditional on whether theblob’s current metageneration does not match the given value.
upload_from_string(data, content_type='text/plain', client=None, predefined_acl=None, if_generation_match=None, if_generation_not_match=None, if_metageneration_match=None, if_metageneration_not_match=None)
Upload contents of this blob from the provided string.
NOTE: The effect of uploading to an existing blob depends on the“versioning” and “lifecycle” policies defined on the blob’sbucket. In the absence of those policies, upload willoverwrite any existing contents.
See theobject versioning andlifecycleAPI documents for details.
Ifuser_project is set on the bucket, bills the API requestto that project.
Parameters
data (bytes* or[str*](https://python.readthedocs.io/en/latest/library/stdtypes.html#str)) – The data to store in this blob. If the value istext, it will be encoded as UTF-8.
content_type (str) – (Optional) Type of content being uploaded. Defaultsto
'text/plain'.client (
ClientorNoneType) – (Optional) The client to use. If not passed, falls backto theclientstored on the blob’s bucket.predefined_acl (str) – (Optional) Predefined access control list
if_generation_match (long) – (Optional) Make the operation conditional on whetherthe blob’s current generation matches the given value.Setting to 0 makes the operation succeed only if thereare no live versions of the blob.
if_generation_not_match (long) – (Optional) Make the operation conditional on whetherthe blob’s current generation does not match the givenvalue. If no live blob exists, the precondition fails.Setting to 0 makes the operation succeed only if thereis a live version of the blob.
if_metageneration_match (long) – (Optional) Make the operation conditional on whether theblob’s current metageneration matches the given value.
if_metageneration_not_match (long) – (Optional) Make the operation conditional on whether theblob’s current metageneration does not match the given value.
property user_project()
Project ID billed for API requests made via this blob.
Derived from bucket’s value.
Return type
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-11-05 UTC.