首页 > 解决方案 > 将文件夹上传到 Google Cloud - Python 2.7

问题描述

我正在尝试将本地计算机中的文件夹上传到谷歌云存储桶。我收到凭据错误。我应该在哪里提供凭据以及其中需要哪些所有信息。

from_dest = '/Users/xyzDocuments/tmp'
gsutil_link = 'gs://bucket-1991'

from google.cloud import storage
try:
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_filename(source_file_name)
    print('File {} uploaded to {}.'.format(source_file_name,destination_blob_name))

except Exception as e:
    print e

错误是

could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://developers.google.com/accounts/do`cs/application-default-credentials.

标签: pythongoogle-cloud-platformgoogle-cloud-storage

解决方案


您需要为您的项目获取应用程序默认凭据并将它们设置为环境变量:

  1. 转到 GCP Console 中的创建服务帐号密钥页面。
  2. 服务帐户下拉列表中,选择新建服务帐户
  3. 在服务帐户名称字段中输入名称。
  4. 角色下拉列表中,选择项目>所有者
  5. 单击创建。一个 JSON 文件,其中包含您下载到计算机的密钥。

然后,设置一个环境变量,当它在本地运行时,它将向您的应用程序提供应用程序凭据:

$ export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

推荐阅读