blob: 96bb622cce9196722ae3e17a496ed7fb73afb0be [file] [log] [blame]
gstepanov5efd15a2015-01-29 17:26:24 +02001import gspread
2import argparse
3import json
4
gstepanov31bb8e42015-01-30 18:00:42 +02005from config import DEFAULT_FILE_PATH, PASSWORD, EMAIL, \
6 WORK_SHEET, DOCUMENT_ID, ROW_COUNT
7from gspread.exceptions import WorksheetNotFound
gstepanov5efd15a2015-01-29 17:26:24 +02008
9
10def load_data(file_name):
11 with open(file_name) as f:
12 data = f.read()
13 return json.loads(data)
14
15
gstepanov31bb8e42015-01-30 18:00:42 +020016#getting worksheet from sheet or create it with specified column names.
17def get_work_sheet(sheet, name, column_names):
18 try:
19 work_sheet = sheet.worksheet(name)
20 except WorksheetNotFound:
21 work_sheet = sheet.add_worksheet(title=name, rows=ROW_COUNT,
22 cols=len(column_names))
23
24 for i in range(1, len(column_names) + 1):
25 work_sheet.update_cell(1, i, column_names[i - 1])
26
27 return work_sheet
28
29
30def get_row_number(work_sheet):
31 num = 2
32
33 while num < work_sheet.row_count and work_sheet.cell(num, 1).value != "":
34 num += 1
35
36 if num == work_sheet.row_count:
37 work_sheet.append_row(["" for x in range(work_sheet.col_count)])
38
39 return num
40
41
42def append_row(work_sheet, row):
43 row_number = get_row_number(work_sheet)
44
45 i = 1
46 for k in row.keys():
47 work_sheet.update_cell(row_number, i, row[k])
48 i += 1
49
50
gstepanov5efd15a2015-01-29 17:26:24 +020051def make_report(data):
52 gc = gspread.login(EMAIL, PASSWORD)
53 sh = gc.open_by_key(DOCUMENT_ID)
gstepanov5efd15a2015-01-29 17:26:24 +020054
gstepanov31bb8e42015-01-30 18:00:42 +020055 work_sheet = get_work_sheet(sh, WORK_SHEET, data.keys())
56 append_row(work_sheet, data)
gstepanov5efd15a2015-01-29 17:26:24 +020057
58
59if __name__ == '__main__':
60 parser = argparse.ArgumentParser()
gstepanov31bb8e42015-01-30 18:00:42 +020061 parser.add_argument('-n', '--name', help='data file path',
62 default=DEFAULT_FILE_PATH)
gstepanov5efd15a2015-01-29 17:26:24 +020063 results = parser.parse_args()
64 data = load_data(results.name)
65 make_report(data)