【问题标题】:Uploading file with python returns Request failed with status code', 403, 'Expected one of', <HTTPStatus.OK: 200>使用 python 上传文件返回 Request failed with status code', 403, 'Expected one', <HTTPStatus.OK: 200>
【发布时间】:2019-05-23 17:23:32
【问题描述】:

blob.upload_from_filename(source) 给出错误

raise 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写的google cloud的例子here

 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)

我使用 gsutil 上传文件,效果很好。
尝试使用也可以正常工作的 python 脚本列出存储桶名称。
我拥有必要的权限并设置了 GOOGLE_APPLICATION_CREDENTIALS。

【问题讨论】:

标签: python google-cloud-storage


【解决方案1】:

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

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

【讨论】:

  • 最佳实践是使用最少的必要权限(可能是您的用例的角色/storage.objectCreator)。存储管理员“授予对存储桶和对象的完全控制权。”。记录角色here
  • @MikePerezOntiveros 是对的。拥有“roles/storage.objectCreator”应该足以满足您的用例。
【解决方案2】:

由于其他答案表明这与权限问题有关,我发现以下命令是为当前登录用户创建默认应用程序凭据的有用方法。

假设您在某台机器上运行此代码时遇到此错误。只需执行以下步骤就足够了:

  • SSH 到正在运行或将要运行代码的 vm。确保您是用户,有权在 Google 存储中上传内容。
  • 运行以下命令: gcloud auth 应用程序默认登录
  • 上述命令将要求通过单击 url 创建令牌。生成令牌并粘贴到 ssh 控制台中。

就是这样。您以该用户身份启动的所有 python 应用程序都将使用此作为存储桶交互的默认凭据。

GCP 快乐 :)

【讨论】:

  • 这应该更高。即使您使用google auth login 正确登录并且即使 gsutil 在命令行上工作,谷歌库似乎默认也不使用任何凭据
【解决方案3】:

这个问题更适合support case

当您收到 403 时,很可能您缺少 IAM 权限,Google Cloud Platform 支持团队将能够检查您的资源和配置。

【讨论】:

    【解决方案4】:

    当谷歌文档不起作用时,这对我有用。我在适当的权限下遇到了同样的错误。

    import pathlib
    import google.cloud.storage as gcs
    
    client = gcs.Client()
    
    #set target file to write to
    target = pathlib.Path("local_file.txt")
    
    #set file to download
    FULL_FILE_PATH = "gs://bucket_name/folder_name/file_name.txt"
    
    #open filestream with write permissions
    with target.open(mode="wb") as downloaded_file:
    
            #download and write file locally 
            client.download_blob_to_file(FULL_FILE_PATH, downloaded_file)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      相关资源
      最近更新 更多