gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:43:08 26 4
gpt4 key购买 nike

我正在使用 Google 的 google-cloud-storage用于 GCS 访问的 Python 包。当我收到 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'
}]
}
}

关于python - 如何在 Python google.cloud.storage 上传方法中访问错误原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59839690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com