user7448870
user7448870

Reputation:

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

I am trying to download a file for the first time from Google Cloud Storage.

I set the path to the googstruct.json service account key file that I downloaded from https://cloud.google.com/storage/docs/reference/libraries#client-libraries-usage-python

Do need to set the authorization to Google Cloud outside the code somehow? Or is there a better "How to use Google Cloud Storage" then the one on the google site?
It seems like I am passing the wrong type to the storage_client = storage.Client() the exception string is below.

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').

MY PYTHON 3.7 CODE

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

I did look at this but I cannot tell if this is my issue. I have tried both.

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

Upvotes: 7

Views: 10840

Answers (1)

John Hanley
John Hanley

Reputation: 81454

This error means that the Json Service Account Credentials that you are trying to use C:\\GoogleCloud\\googstruct.json are corrupt or the wrong type.

The first (or second) line in the file googstruct.json should be "type": "service_account".

Another few items to improve your code:

  1. You do not need to use \\, just use / to make your code easier and cleaner to read.
  2. Load your credentials directly and do not modify environment variables:

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

  1. Wrap API calls in try / except. Stack traces do not impress customers. It is better to have clear, simple, easy to read error messages.

Upvotes: 7

Related Questions