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.

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

    Bucket

  • Returns

    The object’s bucket.

property cache_control()

HTTP ‘Cache-Control’ header for this object.

SeeRFC 7234 andAPI reference docs.

  • Return type

    str orNoneType

property chunk_size()

Get the blob’s default chunk size.

  • Return type

    int orNoneType

  • Returns

    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 orNoneType

  • Returns

    The component count (in case of a composed object) orNone if 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 ofBlob) – blobs whose contents will be composed into this blob.

    • client (Client orNoneType) – (Optional) The client to use. If not passed, falls backto theclient stored 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).Seerequests.Session.request() documentation for details.

property content_disposition()

HTTP ‘Content-Disposition’ header for this object.

SeeRFC 6266 andAPI reference docs.

  • Return type

    str orNoneType

property content_encoding()

HTTP ‘Content-Encoding’ header for this object.

SeeRFC 7231 andAPI reference docs.

  • Return type

    str orNoneType

property content_language()

HTTP ‘Content-Language’ header for this object.

SeeBCP47 andAPI reference docs.

  • Return type

    str orNoneType

property content_type()

HTTP ‘Content-Type’ header for this object.

SeeRFC 2616 andAPI reference docs.

  • Return type

    str orNoneType

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 orNoneType

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 hash

create_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 notNone)

  • 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 theclient stored on the blob’s bucket.

  • Return type

    str

  • 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.GoogleCloudError if 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.

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 (Client orNoneType) – (Optional) The client to use. If not passed, falls backto theclient stored 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

    bytes

  • 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 (Client orNoneType) – (Optional) The client to use. If not passed, falls backto theclient stored 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 toopen.

    • client (Client orNoneType) – (Optional) The client to use. If not passed, falls backto theclient stored 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 orNoneType

  • Returns

    The blob etag orNone if the blob’s resource has not been loaded from the server.

property event_based_hold()

Is an event-based hold active on the object?

SeeAPI reference docs.

If the property is not set locally, returnsNone.

  • Return type

    bool orNoneType

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 (Client orNoneType) – (Optional) The client to use. If not passed, falls backto theclient stored 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).Seerequests.Session.request() documentation for details.

  • Return type

    bool

  • Returns

    True if the blob exists in Cloud Storage.

classmethod from_string(uri, client=None)

Get a constructor for blob object by URI.

  • Parameters

    • uri (str) – The blob uri pass to get blob object.

    • client (Client orNoneType) – (Optional) The client to use.

  • Return type

    google.cloud.storage.blob.Blob

  • Returns

    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 byresource.

    • content_type (str) – (Optional) The content type of the objectreferenced byresource.

    • response_disposition (str) – (Optional) Content disposition ofresponses to requests for the signed URL.For example, to enable the signed URLto initiate a file ofblog.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 (Client orNoneType) – (Optional) The client to use. If not passed, falls backto theclient stored on the blob’s bucket.

    • credentials (google.auth.credentials.Credentials orNoneType) – 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) Ifbucket_bound_hostname is passed as a bare hostname, usethis value as the scheme.https will work only when using a CDN.Defaults to"http".

  • Raises

    ValueError when version is invalid.

  • Raises

    TypeError when expiration is not a valid type.

  • Raises

    AttributeError if credentials is not an instance ofgoogle.auth.credentials.Signing.

  • Return type

    str

  • 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 orNoneType

  • Returns

    The generation of the blob orNone if 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 (Client orNoneType) – (Optional) The client to use. If not passed, falls backto theclient stored on the current object’s bucket.

    • requested_policy_version (int orNoneType) – (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).Seerequests.Session.request() documentation for details.

  • Return type

    google.api_core.iam.Policy

  • Returns

    the policy instance, based on the resource returned from thegetIamPolicy API 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 orNoneType

  • Returns

    The ID of the blob orNone if 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 orNoneType

  • Returns

    The resource name orNone if 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 (Client orNoneType) – (Optional) The client to use. If not passed, falls back to theclient stored on the blob’s bucket.

make_public(client=None)

Update blob’s ACL, granting read access to anonymous users.

  • Parameters

    client (Client orNoneType) – (Optional) The client to use. If not passed, falls back to theclient stored 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 orNoneType

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 hash

property media_link()

Retrieve the media download URI for the object.

Seehttps://cloud.google.com/storage/docs/json_api/v1/objects

  • Return type

    str orNoneType

  • Returns

    The media link for the blob orNone if 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 orNoneType

  • Returns

    The metadata associated with the blob orNone if 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 orNoneType

  • Returns

    The metageneration of the blob orNone if 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 orNoneType

  • Returns

    Mapping of owner’s role/ID, orNone if 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 (Client orNoneType) – the client to use. If not passed, falls back to theclient stored 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).Seerequests.Session.request() documentation for details.

property path()

Getter property for the URL path to this Blob.

  • Return type

    str

  • Returns

    The URL path to this Blob.

static path_helper(bucket_path, blob_name)

Relative URL path for a blob.

  • Parameters

    • bucket_path (str) – The URL path for a bucket.

    • blob_name (str) – The name of the blob.

  • Return type

    str

  • Returns

    The relative URL path forblob_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 (Client orNoneType) – the client to use. If not passed, falls back to theclient stored 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).Seerequests.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.datetime orNoneType

  • Returns

    Datetime object parsed from RFC3339 valid timestamp, orNone if 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 (Client orNoneType) – (Optional) The client to use. If not passed, falls backto theclient stored 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).Seerequests.Session.request() documentation for details.

  • Return type

    tuple

  • Returns

    (token, bytes_rewritten, total_bytes), wheretoken is a rewrite token (None if the rewrite is complete),bytes_rewritten is the number of bytes rewritten so far, andtotal_bytes is 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 orNoneType

  • Returns

    The self link for the blob orNone if 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

  • Return type

    google.api_core.iam.Policy

  • Returns

    the policy instance, based on the resource returned from thesetIamPolicy API request.

property size()

Size of the object, in bytes.

Seehttps://cloud.google.com/storage/docs/json_api/v1/objects

  • Return type

    int orNoneType

  • Returns

    The size of the blob orNone if 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

property temporary_hold()

Is a temporary hold active on the object?

SeeAPI reference docs.

If the property is not set locally, returnsNone.

  • Return type

    bool orNoneType

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 (Client orNoneType) – (Optional) The client to use. If not passed, falls backto theclient stored 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).Seerequests.Session.request() documentation for details.

  • Return type

    list of string

  • Returns

    the permissions returned by thetestIamPermissions API 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.datetime orNoneType

  • Returns

    Datetime object parsed from RFC3339 valid timestamp, orNone if 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.datetime orNoneType

  • Returns

    Datetime object parsed from RFC3339 valid timestamp, orNone if 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 (Client orNoneType) – the client to use. If not passed, falls back to theclient stored 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).Seerequests.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.

property updated()

Retrieve the timestamp at which the object was updated.

Seehttps://cloud.google.com/storage/docs/json_api/v1/objects

  • Return type

    datetime.datetime orNoneType

  • Returns

    Datetime object parsed from RFC3339 valid timestamp, orNone if 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)

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 notNone)

  • 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 readfromfile_obj). If not provided, the upload will beconcluded oncefile_obj is 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 theclient stored on the blob’s bucket.

    • predefined_acl (str) – (Optional) Predefined access control list

  • Raises

    GoogleCloudError if the upload response returns an error status.

upload_from_filename(filename, content_type=None, client=None, predefined_acl=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 notNone)

  • The value stored on the current blob

  • The value given bymimetypes.guess_type

  • 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.

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 theclient stored on the blob’s bucket.

    • predefined_acl (str) – (Optional) Predefined access control list

upload_from_string(data, content_type='text/plain', client=None, predefined_acl=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 (Client orNoneType) – (Optional) The client to use. If not passed, falls backto theclient stored on the blob’s bucket.

    • predefined_acl (str) – (Optional) Predefined access control list

property user_project()

Project ID billed for API requests made via this blob.

Derived from bucket’s value.

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.