Reputation: 1319
I want to update a Blob saved in Google Cloud Storage, the Blob is inside a bucket and I am own. I would like update its content which is only text plain. I have tested a lof of times but I can't get it. My code is:
from google.cloud import storage, exceptions
BUCKET_NAME = 'my-bucket-name'
BLOB_NAME = 'auditoria.txt'
PROJECT_NAME = 'my-project-name'
storage_cliente = storage.Client() # I have a environment variable in windows for auth
def get_bucket_object():
"""Get a bucket"""
bucket = None
try:
bucket = storage_cliente.get_bucket(BUCKET_NAME)
except exceptions.NotFound:
bucket = storage_cliente.create_bucket(bucket_or_name=BUCKET_NAME, project=PROJECT_NAME, location='us-east1')
return bucket
def get_file_log():
"""Retorna un objeto de tipo BLOB presente en un bucket"""
try:
bucket = get_bucket_object()
blob = bucket.get_blob(BLOB_NAME)
if (blob == None):
raise(Exception(f'El blob con nombre {BLOB_NAME} no existe, por favor creelo'))
return blob
except Exception as e:
print(f"Ha ocurrido un error: {e}")
def write_log(msg):
blob = get_file_log()
print(blob.name)
content_blob = blob.download_as_string().decode("utf-8")
blob_txt = content_blob + '\n' + msg
print(blob_txt)
blob.upload_from_string(blob_txt)
print("Blob actualizado correctamente")
write_log(
'WARNING Esta es una prueba mas real'
)
I get this error:
google.api_core.exceptions.BadRequest: 400 POST https://storage.googleapis.com/upload/storage/v1/b/auditorias_servihuella_cali/o?uploadType=multipart: ('Request fa
iled with status code', 400, 'Expected one of', <HTTPStatus.OK: 200>)
So I don't know, what I'm doing wrong?
Upvotes: 0
Views: 1966
Reputation: 1319
Finally, I get an answer:
You can't update an object (Blob) created prevoiusly in a bucket, because the objects in google cloud are immutables. This is a fragment of google documentation:
"Objects are immutable, which means that an uploaded object cannot change throughout its storage lifetime. An object's storage lifetime is the time between successful object creation (upload) and successful object deletion. In practice, this means that you cannot make incremental changes to objects, such as append operations or truncate operations."
More details here: https://cloud.google.com/storage/docs/key-terms#immutability
Upvotes: 3