-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogleDocsAccess.py
179 lines (160 loc) · 6.63 KB
/
googleDocsAccess.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
from __future__ import print_function
import httplib2
import os
import pdb
from collections import OrderedDict
from googleapiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'tools/client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'sheets.googleapis.com-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
from googleapiclient.discovery import build
import pandas as pd
# # # Example usage
# # sheet_id = 'your_google_sheet_id_here'
# # range_name = 'your_range_here' # For example, 'Sheet1!A1:H20'
# data = fetch_data_from_google_sheet(sheet_id, range_name)
# print(data)
#
# def convertListToDict(values):
# exDict = OrderedDict([])
# for n in range(1, len(values)): # loop over all lines in google spread-sheet
# if values[n][0]:
# # print values[n][0]
# # save general information per animal
# exDict[values[n][0]] = OrderedDict([
# ('info', {
# 'type': values[n][1],
# 'mouse': values[n][2],
# 'lineage': values[n][3],
# 'DOB': values[n][4],
#
# }),
# ('dates', {})
# ])
# # save days of experiments, j ... index over dates
# j = n
# while (j < len(values)) and ((not values[j][0]) or (j == n)):
# # create a new entry for a recording date
# if values[j][5]:
# # print values[j][5]
# exDict[values[n][0]]['dates'].update(OrderedDict([
# (values[j][5], {
# 'age': values[j][6],
# # 'weight': values[j][7],
# #'description': values[j][8],
# 'folders': {},
# # 'computer':values[j][10],
# #'recordings': {}
# })
# ]))
# # create new entry for recording session on that date, asociated to a folder '[date]_xxx', m ... index of folder
# m = j
# # check if recording was performed on a given date
# if len(values[m])>5:
# # loop over folders
# #print(m,n,len(values),values[m][5],j)
# #if
# while (m < len(values)) and ((not values[m][5]) or (j == m)):
# try:
# content = values[m][11]
# except IndexError:
# pass
# else:
# #print(m, values[n][0], values[j][5], values[m][10])
# if content != '':
#
# folderName = values[m][11]
# try:
# if values[m-1][11]==values[m][11]:
# folderName=f'{values[m][11]}_bis'
# except IndexError:
# pass
#
# exDict[values[n][0]]['dates'][values[j][5]]['folders'].update(OrderedDict([
# (folderName, {
#
#
# def getExperimentSpreadsheet(structure):
# credentials = get_credentials()
# http = credentials.authorize(httplib2.Http())
# discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
# 'version=v4')
# service = discovery.build('sheets', 'v4', http=http,
# discoveryServiceUrl=discoveryUrl)
#
# if structure== 'DCN':
# spreadsheetId = '11DFnkQ5fnxZFzppuoL9fO5OiryyLDPGd2tDBcKqLgDY'
# rangeName = 'recordings!A:M'
# result = service.spreadsheets().values().get(spreadsheetId=spreadsheetId, range=rangeName).execute()
# values = result.get('values', [])
#
# exptDict = convertListToDict(values)
#
#
# return exptDict
# # a = len(values)
#
# return values
# print(a)
# if not values:
# print('No data found.')
# else:
# print('animal ID, data:')
# for row in values:
# print(len(row))
# if row:
# # Print columns A and E, which correspond to indices 0 and 4.
# print('%s, %s' % (row[0], row[5]))
def getExperimentSpreadsheetV2(rangeName):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
spreadsheetId = '11DFnkQ5fnxZFzppuoL9fO5OiryyLDPGd2tDBcKqLgDY'
range = rangeName
result = service.spreadsheets().values().get(spreadsheetId=spreadsheetId, range=range).execute()
values = result.get('values', [])
# Convert the values to a pandas DataFrame
if values:
# pdb.set_trace()
df = pd.DataFrame(values[1:], columns=values[0])
return df
else:
print("No data found.")
return pd.DataFrame()