How to read and write to a google spreadsheet from heroku using python

Hi all!  This post isn’t about scholcomm or open science so won’t be of interest to most people who used to read this blog back in the day, but I’d kinda like to get back into blogging more and I’m deciding the way to do that is just start blogging more to get the habit back.  Fingers crossed.  :)

Also, all the techies among us have benefitted enormously from others who write posts about their “been there, done this, it worked for me” so I’d like to start giving back a bit more on that front!

Here’s how to get python to read and write from a google spreadsheet, storing the creds in an environment variable so you can run it from heroku for example.

First, read this great post by GREG BAUGUES at Twillo because this solution is just a minor modification to his great instructions.  Go enable the API as he describes, get your credentials file, and don’t forget to go to your google spreadsheet and give permissions to the generated email address as he directs.

Then, set up an environment variable with the value of the contents of the credential file you created, in single quotes, like:

heroku config:add GOOGLE_SHEETS_CREDS_JSON='{
  "type": "service_account",
  "project_id": "my-project",
  "private_key_id": "slkdfjlksdfljksdf",
  "private_key": "-----BEGIN PRIVATE KEY-----\nlsdjflskjdfljsdjfls
...

}
'

 

Then use the code in this gist, replacing the url with the url of your spreadsheet.

Add gspread and oauth2client to your requirements.txt, push it all to github, and it should work!  You can test it with heroku run python google_sheets_from_heroku.py… it should print out the contents of the first sheet of your spreadsheet.

I got it working a day or two ago so the details are a bit hazy now, but I think at some point I was prompted to go to https://console.developers.google.com/ and also give permissions for the “Google Sheets API” in addition to the “Google Drive API” so heads up to try that if you run into any snags.

Anyway, hope that helps somebody!

Long live blogging!