简体   繁体   中英

Flask on GAE - Connect to Google API - Can't use JSON file

I'm fairly new to Flask, GAE and the use of API. I'm trying to build a basic Web App that can connect to one of Google's API.

My folder structure looks like this (I've kept it to the main files):
app-webemotions:
-app.yaml
-main.py
-lib
--sentimentanalysis.py
-static
--credential.json

Everything is working but providing the json file for the credentials. My understanding is that there's a couple of ways to do it:
1) Setting up the GOOGLE_APPLICATION_CREDENTIALS environment variable to the destination of my file in app.yaml
2) Requesting the file through my script (sentimentanalysis.py)

Unfortunately, I haven't been able to make any of those work.

Option 1):
In app.yaml I have the line:

env_variables:
   GOOGLE_APPLICATION_CREDENTIALS: static/key/credentials.json

I then run my code through dev_appserver.py. and get the following error:

ApplicationDefaultCredentialsError: File static/key/credentials.json (pointed by GOOGLE_APPLICATION_CREDENTIALS environment variable) does not exist!

Option 2): I have a line of code in my script sentimentanalysis.py:

  scope = ['https://www.googleapis.com/auth/cloud-platform']
  credentials = ServiceAccountCredentials.from_json_keyfile_name('/static/credentials.json', scope)

And when running the code I get the following error:

    raise IOError(errno.EACCES, 'file not accessible', filename)
IOError: [Errno 13] file not accessible: '/static/credentials.json'
INFO     2016-08-06 04:10:51,678 module.py:788] default: "POST /Sentiment-analysis HTTP/1.1" 500 -

Question:
So it looks like regardless of the method I'm using, I'm not able to provide the right path to the JSON file

My question is to know first if any of the above options is the right option and if yes, what am I doing wrong? If they are not the right options, what would you recommend?

Apologies if this has already been asked, I've tried to find an answer for a few hours now and haven't been able to crack it...

Thank you!

If you are running on Google App Engine, then your code automatically has the credentials it needs. Do not set GOOGLE_APPLICATION_CREDENTIALS and do not call .from_json_keyfile_name. Instead, call:

credentials = GoogleCredentials.get_application_default()

As shown here: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/bigquery/api/getting_started.py

set GOOGLE_APPLICATION_CREDENTIALS=credentials.json use this command if you are using cmd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM