python - 如何访问 Python google.cloud.storage 上传方法中的错误原因?
问题描述
我正在使用 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'
}]
}
}
推荐阅读
- css - CSS Grid 模板行值不会改变
- javascript - 从csv文件中的json输出对象
- javascript - 为什么在减少期间推入原始数组的项目不调用 Array.reduce 函数?
- scala - 如何在 Spark DataFrame SQL 中引用用户定义的集合变量
- google-apps-script - 自动完成应用程序脚本,VS Code 中的 Google 高级服务
- redux-saga - 佐贺总是取消
- php - Sonata Admin - 按关系字段排序
- python - 抓取多个下一页
- c# - EF Core 中每个外键的顺序 ID
- java - Java ThreadPoolExecutor 不创建新线程