使用 python 上传文件返回请求失败,状态代码', 403, '预期之一', <HTTPStatus.OK: 200>

3 python google-cloud-storage

blob.upload_from_filename(source) 给出错误

引发 exceptions.from_http_status(response.status_code, message, >response=response) google.api_core.exceptions.Forbidden: 403 POST > https://www.googleapis.com/upload/storage/v1/b/bucket1-newsdata- > bluetechsoft/o?uploadType=multipart: ('Request failed with status >code', 403, 'Expected one of', )

我在这里遵循用python编写的谷歌云示例!

 from google.cloud import storage

 def upload_blob(bucket, source, des):
    client = storage.Client.from_service_account_json('/path')
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket)
    blob = bucket.blob(des)
    blob.upload_from_filename(source)
Run Code Online (Sandbox Code Playgroud)

我使用 gsutil 上传文件,工作正常。
尝试使用 python 脚本列出存储桶名称,该脚本也工作正常。
我有必要的权限和 GOOGLE_APPLICATION_CREDENTIALS 设置。

小智 7

这一切都不起作用,因为我在 GCP 中使用的服务帐户没有权限 storage admin

允许storage admin我的服务帐户解决了我的问题。

  • 最佳实践是使用必要的最少权限(对于您的用例可能是角色/storage.objectCreator)。存储管理员“授予对存储桶和对象的完全控制权。”。角色记录在 [此处](https://cloud.google.com/storage/docs/access-control/iam-roles) (3认同)