I want to deploy a flask application on heroku and in the flask app I use the Google Sheets API with gspread. To authenticate you get a client_secret.json file which you need to insert to ServiceAccountCredentials.from_json_keyfile_name()
. As you do it, I saved all the variables from the json file as enviroment variables and get them like this:
def create_keyfile_dict(): variables_keys = { "type": os.environ.get("SHEET_TYPE"), "project_id": os.environ.get("SHEET_PROJECT_ID"), "private_key_id": os.environ.get("SHEET_PRIVATE_KEY_ID"), "private_key": os.environ.get("SHEET_PRIVATE_KEY"), "client_email": os.environ.get("SHEET_CLIENT_EMAIL"), "client_id": os.environ.get("SHEET_CLIENT_ID"), "auth_uri": os.environ.get("SHEET_AUTH_URI"), "token_uri": os.environ.get("SHEET_TOKEN_URI"), "auth_provider_x509_cert_url": os.environ.get("SHEET_AUTH_PROVIDER_X509_CERT_URL"), "client_x509_cert_url": os.environ.get("SHEET_CLIENT_X509_CERT_URL") } return variables_keys scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"] creds = ServiceAccountCredentials.from_json_keyfile_name(create_keyfile_dict(), scope)
But then I geht the Error:
with open(filename, 'r') as file_obj: FileNotFoundError: [Errno 2] No such file or directory: 'client_secret'
Because gspread wants a file right there and not a dictionary which my function returns. So the question is more or less (if there is no better way) how I should get the enviroment variables to a file which is only on heroku and not on GitHub and can be read by gspread.
Advertisement
Answer
Rather than using the method that comes with ServiceAccountCredentials
intended to read from the JSON credentials file that google sends you, you can make use of this method: