0

I am try to get google sheet api authentication using pygsheets in the Replit. I saved the credentials json content into the "Secrets" function of Replit, the code is as below:

import pygsheets
import os
import json

creds = json.loads(os.environ.get('GDRIVE_API_CREDENTIALS'))
with open('gcreds.json', 'w') as fp:
    json.dump(creds, fp)
gc = pygsheets.authorize(service_account_env_var = 'gcreds.json')

The 'GDRIVE_API_CREDENTIALS' is a below when i open the raw editor of Secrets:

"GDRIVE_API_CREDENTIALS": "{\"type\": \"service_account\", \"project_id\": \"xxx\", \"private_key_id\": \"xxx\", \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nxxx\\n-----END PRIVATE KEY-----\\n\", \"client_email\": \"xxx\", \"client_id\": \"xxx\", \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\", \"token_uri\": \"https://oauth2.googleapis.com/token\", \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\", \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/xxx.iam.gserviceaccount.com\"}"

After running the .py file it gives me a KeyError: 'gcreds.json'

beaconho
  • 17
  • 5
  • Although I'm not sure about your actual environment, what is `gcreds.json` of `gc = pygsheets.authorize(service_account_env_var = 'gcreds.json')`? For example, in your script, is that `gc = pygsheets.authorize(service_account_env_var = 'GDRIVE_API_CREDENTIALS')`? [Ref](https://pygsheets.readthedocs.io/en/stable/authorization.html#environment-variables) – Tanaike Jan 05 '23 at 04:49
  • I am using the Replit environment, since i need to key my keys private so i keep them in the Secret function there, which need to be called by `os.environ.get` to get the keys – beaconho Jan 05 '23 at 04:59
  • but you have reminded me, i have changed the `gc = pygsheets.authorize(service_account_env_var = 'gcreds.json')` to `gc = pygsheets.authorize(service_file= 'gcreds.json')`, there is no error now, let me do some work in that to see if this work, thanks! – beaconho Jan 05 '23 at 05:00
  • I found that your solution works, and my "solution" defeated my security purpose, thanks a lot! – beaconho Jan 05 '23 at 05:23

0 Answers0