【问题标题】:Update Blob in Google Storage using Python SDK使用 Python SDK 更新 Google Storage 中的 Blob
【发布时间】:2020-10-14 20:20:14
【问题描述】:

我想更新保存在 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>)

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

【问题讨论】:

    标签: python google-cloud-platform google-cloud-storage google-api-python-client


    【解决方案1】:

    终于,我得到了答案:

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

    “对象是不可变的,这意味着上传的对象在其存储生命周期内不能更改。对象的存储生命周期是从成功创建(上传)对象到成功删除对象之间的时间。实际上,这意味着您不能增量对对象的更改,例如追加操作或截断操作。”

    更多详情:https://cloud.google.com/storage/docs/key-terms#immutability

    【讨论】:

    • 您当然可以上传新内容来完全替换现有对象,给它一个新版本。您只需修改一个对象并让版本保持不变。您必须阅读这些文档所说的:“但是,可以替换存储在 Cloud Storage 中的对象,并且这样做是原子发生的
    • @DougStevenson 你有上面提到的代码示例吗?
    猜你喜欢
    • 2017-03-17
    • 2021-08-26
    • 1970-01-01
    • 2023-04-07
    • 2019-04-25
    • 2017-10-17
    • 2019-05-31
    • 2021-07-11
    • 2021-02-15
    相关资源
    最近更新 更多