Google Cloud 授权在 Python 3 中持续失败 - 类型为 None,预期为 ('authorized_user', 'service_account') 之一

7 google-cloud-storage google-oauth

我第一次尝试从 Google 云存储下载文件。

我设置了从https://cloud.google.com/storage/docs/reference/libraries#client-libraries-usage-python下载的 googstruct.json 服务帐户密钥文件的路径

是否需要在代码之外设置对 Google Cloud 的授权?或者是否有比谷歌网站上更好的“如何使用谷歌云存储”?
看来我将错误的类型传递给storage_client = storage.Client() 异常字符串如下。

发生异常:google.auth.exceptions.DefaultCredentialsError 文件 C:\Users\Cary\Documents\Programming\Python\QGIS\GoogleCloud\googstruct.json 没有有效类型。类型为 None,应为 ('authorized_user', 'service_account') 之一。

我的 Python 3.7 代码

from google.cloud import storage
import os

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="C:\\GoogleCloud\\googstruct.json"

# Instantiates a client
storage_client = storage.Client()
bucket_name = 'structure_ssi'
destination_file_name = "C:\\Users\\18809_PIPEM.shp"
source_blob_name = '18809_PIPEM.shp'
download_blob(bucket_name, source_blob_name, destination_file_name)

def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(source_blob_name)

    blob.download_to_filename(destination_file_name)

    print('Blob {} downloaded to {}.'.format(
        source_blob_name,
        destination_file_name
        )
    )
Run Code Online (Sandbox Code Playgroud)

我确实看过这个,但我不知道这是否是我的问题。我两种都试过了。

('意外的凭据类型', None, '预期', 'service_account') 与 oauth2client (Python)

Joh*_*ley 6

此错误意味着您尝试使用的 Json 服务帐户凭据C:\\GoogleCloud\\googstruct.json已损坏或类型错误。

文件中的第一行(或第二行)googstruct.json应该是"type": "service_account".

另外一些可以改进代码的项目:

  1. 您不需要使用\\,只需使用/来让您的代码更容易、更清晰地阅读。
  2. 直接加载您的凭据,不要修改环境变量:

storage_client = storage.Client.from_service_account_json('C:/GoogleCloud/googstruct.json')

  1. 将 API 调用包装在 try/ except 中。堆栈跟踪不会给客户留下深刻的印象。最好有清晰、简单、易于阅读的错误消息。