首页 > 解决方案 > 如何访问 Python google.cloud.storage 上传方法中的错误原因?

问题描述

我正在使用 Google 的google-cloud-storagePython 包进行 GCS 访问。当我收到 403 错误时,可能有很多不同的原因。默认情况下,Google 的 SDK 仅提供此消息:

('Request failed with status code', 403, 'Expected one of', <HTTPStatus.OK: 200>)")

使用调试器,我可以更深入地查看库并找到_upload.py一个_process_response可以找到真正 HTTP 响应的方法,结果中包含以下消息:

"message": "$ACCOUNT does not have storage.objects.delete access to $BLOB."

问:有什么方法可以访问这个更有用的错误代码或原始响应?

我希望向用户展示过期凭据和尝试执行您的凭据不允许的操作之间的区别。

标签: pythongoogle-cloud-platformgoogle-cloud-storagegoogle-cloud-python

解决方案


你用的是什么版本的google-cloud-storage?使用最新的,以及这个例子:

from google.cloud import storage
client = storage.Client.from_service_account_json('service-account.json')
bucket = client.get_bucket('my-bucket-name')
blob = bucket.get_blob('test.txt')
try:
    blob.delete()
except Exception as e:
    print(e)

它打印以下内容:

403 DELETE https://storage.googleapis.com/storage/v1/b/my-bucket-name/o/test.txt?generation=1579627133414449: $ACCOUNT does not have storage.objects.delete access to my-bucket-name/test.txt.

这里的字符串表示大致相同e.message

>>> e.message
'DELETE https://storage.googleapis.com/storage/v1/b/my-bucket-name/o/test.txt?generation=1579627133414449: $ACCOUNT does not have storage.objects.delete access to my-bucket-name/test.txt.'

如果你想要更多的结构,你可以使用e._response.json()

>>> e._response.json()
{
    'error': {
        'code': 403,
        'message': '$ACCOUNT does not have storage.objects.delete access to my-bucket-name/test.txt/test.txt.',
        'errors': [{
            'message': '$ACCOUNT does not have storage.objects.delete access to my-bucket-name/test.txt/test.txt.',
            'domain': 'global',
            'reason': 'forbidden'
        }]
    }
}

推荐阅读