This repository has been archived by the owner on Aug 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathimporter.py
57 lines (45 loc) · 1.54 KB
/
importer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from csv import reader
from distutils.util import strtobool
from os import getenv
import gspread
from google.oauth2.service_account import Credentials
# Input vars
csv_path = getenv("INPUT_CSV_PATH")
spreadsheet_id = getenv("INPUT_SPREADSHEET_ID")
worksheet_id = int(getenv("INPUT_WORKSHEET"))
append_content = strtobool(getenv("INPUT_APPEND_CONTENT", "False"))
service_account_info = {
"token_uri": "https://oauth2.googleapis.com/token",
"client_email": getenv("INPUT_GOOGLE_SERVICE_ACCOUNT_EMAIL"),
"private_key": getenv("INPUT_GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY").replace(
"\\n", "\n"
),
}
scopes = [
"https://spreadsheets.google.com/feeds",
]
def next_available_row(worksheet):
"""
Return the next available row in the first column
gspread doesn't have a method to return the last row used
"""
str_list = list(filter(None, worksheet.col_values(1)))
return str(len(str_list) + 1)
# Read csv file as a list of lists
with open(csv_path, "r") as read_obj:
# pass the file object to reader() to get the reader object
csv_reader = reader(read_obj)
# Pass reader object to list() to get a list of lists
list_of_rows = list(csv_reader)
creds = Credentials.from_service_account_info(
service_account_info, scopes=scopes
)
client = gspread.authorize(creds)
spreadsheet = client.open_by_key(spreadsheet_id)
ws = spreadsheet.get_worksheet(worksheet_id)
if append_content:
start_from = f"A{next_available_row(ws)}"
else:
ws.clear()
start_from = "A1"
ws.update(start_from, list_of_rows)