簡體   English   中英

使用 python 上傳文件返回請求失敗,狀態代碼為 &#39;, 403, &#39;Expected one of&#39;,<HTTPStatus.OK: 200>

[英]Uploading file with python returns Request failed with status code', 403, 'Expected one of', <HTTPStatus.OK: 200>

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)

我使用 gsutil 上傳文件,工作正常。
嘗試使用 python 腳本列出存儲桶名稱,該腳本也工作正常。
我有必要的權限和 GOOGLE_APPLICATION_CREDENTIALS 設置。

這一切都不起作用,因為我在 GCP 中使用的服務帳戶中沒有storage admin權限

允許storage admin訪問我的服務帳戶解決了我的問題。

由於其他答案表明這與權限問題有關,我發現以下命令是為當前登錄的用戶創建默認應用程序憑據的有用方法。

假設您在某台機器上運行此代碼時遇到此錯誤。 只需以下步驟就足夠了:

  • SSH 到正在運行或將運行代碼的虛擬機。 確保您是用戶,有權在谷歌存儲中上傳內容。
  • 運行以下命令:gcloud auth application-default login
  • 上面的命令將要求通過單擊 url 創建令牌。 生成令牌並粘貼到 ssh 控制台中。

就是這樣。 您所有的 Python 應用程序都以該用戶身份啟動,將使用它作為存儲桶交互的默認憑據。

快樂 GCP'ing :)

這個問題更適合支持案例

當您收到 403 時,很可能您缺少 IAM 權限,Google Cloud Platform 支持團隊將能夠檢查您的資源和配置。

當谷歌文檔不起作用時,這對我有用。 我在適當的權限下遇到了同樣的錯誤。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM