如何访问Python google.cloud.storage上载方法中的错误原因?

2024-09-28 03:21:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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."

Q:有没有办法访问这个更有用的错误代码或原始响应?

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


Tags: cloud消息requeststatus错误withgooglesdk
1条回答
网友
1楼 · 发布于 2024-09-28 03:21:58

您使用的是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'
        }]
    }
}

相关问题 更多 >

    热门问题