Search code examples
pythonauthenticationgoogle-speech-api

Setting Environmental variable issue


I'm getting an auth error with my google api test, the code to set the environmental variable works alone, however when used in conjunction with the google test code the auth fails. I was also able to get the test code to work by running an EXPORT command in shell. For convenience, I'd like to be able to set the auth in my scripts.

 #This program will test the google speech api
 #while setting the environmental variable for the
 #authentication .json file and then authenticating

 import os

 # Imports the Google Cloud client library
 from google.cloud import language
 from google.cloud.language import enums
 from google.cloud.language import types

 # My code sets the authentication env variable
 os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = str('home/kyle/Security/test.json')

 # Instantiates a client
 client = language.LanguageServiceClient()

 # The text to analyze
 text = u'Hello, world!'
 document = types.Document(
     content=text,
     type=enums.Document.Type.PLAIN_TEXT)

 # Detects the sentiment of the text
 sentiment = client.analyze_sentiment(document=document).document_sentiment

 print('Text: {}'.format(text))
 print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))

The error:

   File "/home/kyle/python projects/googleSpeech/test/venv/lib/python3.5/site-packages/google/auth/_default.py", line 142, in _get_explicit_environ_credentials
os.environ[environment_vars.CREDENTIALS])
   File "/home/kyle/python projects/googleSpeech/test/venv/lib/python3.5/site-packages/google/auth/_default.py", line 67, in _load_credentials_from_file
'File {} was not found.'.format(filename))
 google.auth.exceptions.DefaultCredentialsError: File home/kyle/Security/test.json was not found.

EDIT now exporting the json file doesnt work I ran this code to test reading the .json file

 fd = open(‘/home/kyle/Security/test.json’)
 dat = fd.read()
 fd.close()

Result:

 SyntaxError: Non-ASCII character '\xe2' in file testRead.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

Solution

  • The issue required me to regenerate a new json key from the api console with the project owner permissions its working now no code change required