Google 云授权一直失败并显示 Python 3 - 类型为 None,应为 ('authorized_user'、'service_account')

Google Cloud authorization keeps failing with Python 3 - Type is None, expected one of ('authorized_user', 'service_account')

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

我设置了从 https://cloud.google.com/storage/docs/reference/libraries#client-libraries-usage-python

下载的 googstruct.json 服务帐户密钥文件的路径

是否需要以某种方式在代码之外设置对Google Cloud 的授权?或者有比 google 网站上更好的 "How to use Google Cloud Storage" 吗?
好像我将错误的类型传递给 storage_client = storage.Client() 异常字符串如下。

Exception has occurred: google.auth.exceptions.DefaultCredentialsError
The file C:\Users\Cary\Documents\Programming\Python\QGIS\GoogleCloud\googstruct.json does not have a valid type. 
Type is None, expected one of ('authorized_user', 'service_account').

我的PYTHON3.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))

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

('Unexpected credentials type', None, 'Expected', 'service_account') with oauth2client (Python)

此错误意味着您尝试使用的 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. 在 try / except 中包装 API 调用。堆栈跟踪不会给客户留下深刻印象。错误信息最好清晰、简单、易读。