Google Cloud授权使用Python 3失败 - 类型为无,预期为('authorized_user','service_account')之一

问题描述 投票:0回答:1

我正在尝试从Google云端存储中首次下载文件。

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

是否需要以某种方式在代码之外设置Google Cloud的授权?或者是否有更好的“如何使用谷歌云存储”然后谷歌网站上的那个? 好像我将错误的类型传递给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').

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

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

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

google-cloud-storage google-authentication
1个回答
1
投票

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

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

另外几个改进代码的项目:

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

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

  1. 在try / except中包装API调用。堆栈跟踪不会给客户留下深刻印象。最好有清晰,简单,易读的错误消息。
© www.soinside.com 2019 - 2024. All rights reserved.