使用 Python SDK 更新 Google 存储中的 Blob

Update Blob in Google Storage using Python SDK

我想更新保存在 Google Cloud Storage 中的一个 Blob,这个 Blob 在一个桶里,我是自己的。我想更新它的内容,它只是纯文本。我已经测试了很多次,但我无法得到它。我的代码是:

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

我收到这个错误:

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

所以我不知道,我做错了什么?

终于得到答案了:

您无法更新先前在存储桶中创建的对象 (Blob),因为 google 云中的对象是不可变的。这是 google 文档的片段:

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

此处有更多详细信息:https://cloud.google.com/storage/docs/key-terms#immutability