Skip to content

Instantly share code, notes, and snippets.

@alfasin
Last active May 13, 2016 05:13
Show Gist options
  • Save alfasin/27af3ec1ea13c11d3aaa6271f2fef081 to your computer and use it in GitHub Desktop.
Save alfasin/27af3ec1ea13c11d3aaa6271f2fef081 to your computer and use it in GitHub Desktop.
#!/apps/python/bin/python
import logging
import gspread
from creds import API_ACCESS_KEY, get_client_email, get_private_key
logger = logging.getLogger('nflx.' + __name__)
headers = {
'Authorization': 'Token token={0}'.format(API_ACCESS_KEY),
'Content-type': 'application/json',
}
def authenticate_and_get_spreadsheet():
scope = ['https://spreadsheets.google.com/feeds']
client_email = get_client_email()
private_key = get_private_key()
credentials = SignedJwtAssertionCredentials(client_email, private_key, scope)
gc = gspread.authorize(credentials)
return gc
def open_worksheet_for_date(title, ss):
try:
wks = ss.add_worksheet(title=title, rows="1000", cols="30")
except Exception, e:
logger.info("failed to add a worksheet: [%s]", e)
wks = ss.worksheet(title=title)
logger.info("opened the existing worksheet")
return wks
def open_sheet(title):
"""
open a new worksheet with the title as the start-date
:param since: start-date
:return: worksheet
"""
try:
ss = get_spreadsheet()
wks = open_worksheet_for_date(title, ss)
except Exception, ex:
logger.error("failed to login google-docs: [%s]", ex)
raise ex
return wks
def get_spreadsheet():
gc = authenticate_and_get_spreadsheet()
ss = gc.open_by_key('1FxDclu1hbMrfQOPC-f93CccebuElP9YR5NMzl4AahDk') # document key
return ss
def write_headers(wks):
"""
write the headers of the spreadsheet
:param wks: worksheet
:return: None
"""
wks.update_acell('A1', 'A')
wks.update_acell('B1', 'B')
wks.update_acell('C1', 'C')
def update_row(cell_list, data, row):
"""
:param cell_list: list of cell objects to write the data to
:param data: the data to be written
:param row: the row number
:return: None
"""
start_index = row * 3 # we have 3 columns
for i in range(3):
cell_list[start_index + i].value = data[i]
def save_to_spreadsheet():
try:
title = 'test'
wks = open_sheet(title)
write_headers(wks)
cell_list = wks.range('A2:L100') # fetch block of cell from the spreadsheet to write the data
count = update_row(cell_list, [1, 2, 3], 3)
except Exception, ex:
logger.error("Exception: %s", ex)
if __name__ == "__main__":
save_to_spreadsheet()
@alfasin
Copy link
Author

alfasin commented May 13, 2016

This example uses package: gspread. It's pretty hacky but it does the job.
"document key" is part of the URL, in order to write to the spreadsheet you should create it manually, grab the document-key from the url of the spreadsheet and use it here (line 50).

Other than that you should add retry mechanism (with exponential backoff) to your calls because google throttles the requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment