-
Notifications
You must be signed in to change notification settings - Fork 0
/
gsheet.py
41 lines (39 loc) · 1.72 KB
/
gsheet.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
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
class gsheet(object):
def __init__(self):
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
self.creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
self.creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not self.creds or not self.creds.valid:
if self.creds and self.creds.expired and self.creds.refresh_token:
self.creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
self.creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(self.creds, token)
self.service = build('sheets', 'v4', credentials=self.creds)
def add(self,sheetid,sheetrange,ivalue):
# Call the Sheets API
sheet = self.service.spreadsheets()
values = []
values.append(ivalue)
body = {
'values': values
}
result = sheet.values().append(
spreadsheetId=sheetid, range=sheetrange,
valueInputOption='RAW', body=body).execute()