繁体   English   中英

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

[英]How to access error reason in Python google.cloud.storage upload methods?

我正在使用 Google 的google-cloud-storage Python 包进行 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."

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM